From ba18c5249db5475dd2088ffe01b32d13e352da11 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Mon, 4 Mar 2013 13:18:16 +0200 Subject: [PATCH 01/15] Added the chapter two assignments --- austinov.02.setting_out_to_cpp/01_address.cpp | 11 ++++++++++ .../02_distance.cpp | 14 ++++++++++++ austinov.02.setting_out_to_cpp/03_mices.cpp | 22 +++++++++++++++++++ austinov.02.setting_out_to_cpp/04_months.cpp | 13 +++++++++++ austinov.02.setting_out_to_cpp/05_degrees.cpp | 21 ++++++++++++++++++ .../06_lightyrs.cpp | 18 +++++++++++++++ austinov.02.setting_out_to_cpp/07_time.cpp | 19 ++++++++++++++++ 7 files changed, 118 insertions(+) create mode 100644 austinov.02.setting_out_to_cpp/01_address.cpp create mode 100644 austinov.02.setting_out_to_cpp/02_distance.cpp create mode 100644 austinov.02.setting_out_to_cpp/03_mices.cpp create mode 100644 austinov.02.setting_out_to_cpp/04_months.cpp create mode 100644 austinov.02.setting_out_to_cpp/05_degrees.cpp create mode 100644 austinov.02.setting_out_to_cpp/06_lightyrs.cpp create mode 100644 austinov.02.setting_out_to_cpp/07_time.cpp diff --git a/austinov.02.setting_out_to_cpp/01_address.cpp b/austinov.02.setting_out_to_cpp/01_address.cpp new file mode 100644 index 0000000..059674d --- /dev/null +++ b/austinov.02.setting_out_to_cpp/01_address.cpp @@ -0,0 +1,11 @@ +// nameaddr.cpp displays the name and address of it's author + +#include + +int main() +{ + using namespace std; + cout << "Artem Ustinov" << endl; + cout << "artem@ustinov.org.ua" << endl; + return 0; +} diff --git a/austinov.02.setting_out_to_cpp/02_distance.cpp b/austinov.02.setting_out_to_cpp/02_distance.cpp new file mode 100644 index 0000000..e3ab0fa --- /dev/null +++ b/austinov.02.setting_out_to_cpp/02_distance.cpp @@ -0,0 +1,14 @@ +// fl2yd.cpp asks the length in furlong and converts to yards + +#include + +int main(void) +{ + int l; + l = 0; + std::cout << "Please specify length in furlolgs: "; + std::cin >> l; + std::cout << "The converted length is "; + std::cout << l * 220 << " yards" << std::endl; + return 0; +} diff --git a/austinov.02.setting_out_to_cpp/03_mices.cpp b/austinov.02.setting_out_to_cpp/03_mices.cpp new file mode 100644 index 0000000..98ae58d --- /dev/null +++ b/austinov.02.setting_out_to_cpp/03_mices.cpp @@ -0,0 +1,22 @@ +// fourlines.cpp produces four lines using three functions + +#include + +void first(void) +{ + std::cout << "Three blind mice" << std::endl; +} + +void second(void) +{ + std::cout << "See how they run" << std::endl; +} + +int main(void) +{ + first(); + first(); + second(); + second(); + return 0; +} diff --git a/austinov.02.setting_out_to_cpp/04_months.cpp b/austinov.02.setting_out_to_cpp/04_months.cpp new file mode 100644 index 0000000..c22c64a --- /dev/null +++ b/austinov.02.setting_out_to_cpp/04_months.cpp @@ -0,0 +1,13 @@ +// age2mnth.cpp asks you the age and then shows it in months + +#include + +int main(void) +{ + int age; + age = 0; + std::cout << "Please enter your age: "; + std::cin >> age; + std::cout << "Your age in month is " << age * 12 << std::endl; + return 0; +} diff --git a/austinov.02.setting_out_to_cpp/05_degrees.cpp b/austinov.02.setting_out_to_cpp/05_degrees.cpp new file mode 100644 index 0000000..4988fdc --- /dev/null +++ b/austinov.02.setting_out_to_cpp/05_degrees.cpp @@ -0,0 +1,21 @@ +// cd2fd.cpp asks you the celsium degrees and converts to farenheit + +#include + +int c2f(float c) +{ + return 1.8 * c + 32.0; +} + +int main(void) +{ + float c; + std::cout << "Please enter a Celsius value: "; + std::cin >> c; + std::cout << c << " degrees Celsius is " << c2f(c); + std::cout << " degrees Farenheit." << std::endl; + std::cout << "For reference,here is the formula for making the "; + std::cout << "conversion:\nFahrenheit = "; + std::cout << "1.8 × degrees Celsius + 32.0" << std::endl; + return 0; +} diff --git a/austinov.02.setting_out_to_cpp/06_lightyrs.cpp b/austinov.02.setting_out_to_cpp/06_lightyrs.cpp new file mode 100644 index 0000000..e9a0e84 --- /dev/null +++ b/austinov.02.setting_out_to_cpp/06_lightyrs.cpp @@ -0,0 +1,18 @@ +// fl2yd.cpp asks the length in furlong and converts to yards + +#include + +int ly2au(float d) +{ + return 63240 * d; +} + +int main(void) +{ + float d; + std::cout << "Enter the number in light years: "; + std::cin >> d; + std::cout << d << " light years = " << ly2au(d); + std::cout << " astronomical units." << std::endl; + return 0; +} diff --git a/austinov.02.setting_out_to_cpp/07_time.cpp b/austinov.02.setting_out_to_cpp/07_time.cpp new file mode 100644 index 0000000..0f77d03 --- /dev/null +++ b/austinov.02.setting_out_to_cpp/07_time.cpp @@ -0,0 +1,19 @@ +// hour:min.cpp displays the entered hour and minute in HH:MM format + +#include + +void pretty_print(int hh, int mm) +{ + std::cout << "Time: " << hh << ":" << mm << std::endl; +} + +int main(void) +{ + int hh, mm; + std::cout << "Enter the number of hours: "; + std::cin >> hh; + std::cout << "Enter the number of minutes: "; + std::cin >> mm; + pretty_print(hh, mm); + return 0; +} From e8665c7dc239dce571461c1974219a5cd5cd2f35 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 5 Mar 2013 22:13:17 +0200 Subject: [PATCH 02/15] Chapter 3 assignments --- austinov.03.dealing_with_data/01_bmi.cpp | 34 ++++++++++++++++++++ austinov.03.dealing_with_data/02_degrees.cpp | 34 ++++++++++++++++++++ austinov.03.dealing_with_data/03_secs.cpp | 28 ++++++++++++++++ austinov.03.dealing_with_data/04_pops.cpp | 22 +++++++++++++ austinov.03.dealing_with_data/05_mpg.cpp | 23 +++++++++++++ austinov.03.dealing_with_data/06_lkm2mpg.cpp | 21 ++++++++++++ 6 files changed, 162 insertions(+) create mode 100644 austinov.03.dealing_with_data/01_bmi.cpp create mode 100644 austinov.03.dealing_with_data/02_degrees.cpp create mode 100644 austinov.03.dealing_with_data/03_secs.cpp create mode 100644 austinov.03.dealing_with_data/04_pops.cpp create mode 100644 austinov.03.dealing_with_data/05_mpg.cpp create mode 100644 austinov.03.dealing_with_data/06_lkm2mpg.cpp diff --git a/austinov.03.dealing_with_data/01_bmi.cpp b/austinov.03.dealing_with_data/01_bmi.cpp new file mode 100644 index 0000000..a152d80 --- /dev/null +++ b/austinov.03.dealing_with_data/01_bmi.cpp @@ -0,0 +1,34 @@ +// bmi.cpp makes different conversions and calculates the BMI + +#include + +int main() +{ + int h_ft = 0; + int h_in = 0; + int w_lbs = 0; + + std::cout << "This program wants to calculate your BMI" << std::endl; + std::cout << "Please enter your height in feet and inches..."; + std::cout << std::endl << "Enter feet: "; + std::cin >> h_ft; + std::cout << "And inches: "; + std::cin >> h_in; + std::cout << "Please also enter your weight in pounds: "; + std::cin >> w_lbs; + + // getting total height in inches + h_in += h_ft / 12; + + // defining the multipliers for Height and Weight + const float H_Mult = 0.0254; + const float W_Mult = 2.2; + + // converting to meters and kilograms accordingly + float h_m = H_Mult * h_in; + float w_kg = W_Mult * w_lbs; + + std::cout << "The BMI is " << w_kg / (h_m * h_m) << std::endl; + + return 0; +} diff --git a/austinov.03.dealing_with_data/02_degrees.cpp b/austinov.03.dealing_with_data/02_degrees.cpp new file mode 100644 index 0000000..89425dd --- /dev/null +++ b/austinov.03.dealing_with_data/02_degrees.cpp @@ -0,0 +1,34 @@ +// degrees.cpp converts D-M-S of ARC into decimal Degrees + +#include + +int main() +{ + int i_d, i_m, i_s = 0; + + std::cout << "I will convert your coordinate into degrees" << std::endl; + std::cout << "Please enter it in degrees, minutes and seconds..."; + std::cout << std::endl << "Enter degrees: "; + std::cin >> i_d; + std::cout << "and minutes: "; + std::cin >> i_m; + std::cout << "and seconds: "; + std::cin >> i_s; + + // defining the multipliers + const int S_IN_M = 60; + const int S_IN_D = 3600; + + // the result should be floating point + double d_res; + + std::cout << i_d << " degrees, "; + std::cout << i_m << " minutes, "; + std::cout << i_s << " seconds = "; + + std::cout.precision(7); // setting the precision for result + std::cout << (i_d + static_cast(i_m * S_IN_M + i_s) / S_IN_D); + std::cout << " decimal degrees." << std::endl; + + return 0; +} diff --git a/austinov.03.dealing_with_data/03_secs.cpp b/austinov.03.dealing_with_data/03_secs.cpp new file mode 100644 index 0000000..c9677e9 --- /dev/null +++ b/austinov.03.dealing_with_data/03_secs.cpp @@ -0,0 +1,28 @@ +// secs.cpp converts seconds into days, hours, minutes and seconds + +#include + +int main() +{ + int i_s = 0; + + std::cout << "I'll show you seconds in days, hrs, min, sec..."; + std::cout << std::endl << "Enter seconds: "; + std::cin >> i_s; + + // defining the multipliers + const int S_IN_M = 60; + const int S_IN_H = S_IN_M * 60; + const int S_IN_D = S_IN_H * 24; + + std::cout << i_s << " seconds equals to "; + std::cout << i_s / S_IN_D << " days, "; + i_s = i_s % S_IN_D; + std::cout << i_s / S_IN_H << " hours, "; + i_s = i_s % S_IN_H; + std::cout << i_s / S_IN_M << " minutes and "; + i_s = i_s % S_IN_M; + std::cout << i_s << " seconds." << std::endl; + + return 0; +} diff --git a/austinov.03.dealing_with_data/04_pops.cpp b/austinov.03.dealing_with_data/04_pops.cpp new file mode 100644 index 0000000..af4bc0c --- /dev/null +++ b/austinov.03.dealing_with_data/04_pops.cpp @@ -0,0 +1,22 @@ +// pops.cpp shows you the percentage of the second number in first + +#include + +int main() +{ + unsigned long long ull_world = 0; + unsigned long ul_ukraine = 0; + + std::cout << "I'll show you the percentage..." << std::endl;; + std::cout << "Specify the world population (is around 7B): "; + std::cin >> ull_world; + std::cout << "And the population of Ukraine (around 45M): "; + std::cin >> ul_ukraine; + + std::cout << "The population of Ukraine is "; + std::cout.precision(4); + std::cout << static_cast(ul_ukraine) / (ull_world / 100); + std::cout << "\% of World's population." << std::endl; + + return 0; +} diff --git a/austinov.03.dealing_with_data/05_mpg.cpp b/austinov.03.dealing_with_data/05_mpg.cpp new file mode 100644 index 0000000..03477da --- /dev/null +++ b/austinov.03.dealing_with_data/05_mpg.cpp @@ -0,0 +1,23 @@ +// mpg.cpp counts the fuel consumption in mpg or lp100km + +#include + +int main() +{ + unsigned int ui_dist = 0; + unsigned int ui_fuel = 0; + + std::cout << "I can count the Fuel Consumption." << std::endl;; + std::cout << "Enter the mileage (in miles or km): "; + std::cin >> ui_dist; + std::cout << "And specify the fuel amount (in gal or liter): "; + std::cin >> ui_fuel; + + std::cout << "The average consumption is around "; + std::cout.precision(3); + std::cout << ui_dist / ui_fuel << " mpg," << std::endl;; + std::cout << "or " << 100 * ui_fuel / static_cast(ui_dist); + std::cout << " liters per 100 km accordingly." << std::endl; + + return 0; +} diff --git a/austinov.03.dealing_with_data/06_lkm2mpg.cpp b/austinov.03.dealing_with_data/06_lkm2mpg.cpp new file mode 100644 index 0000000..d6b0a1b --- /dev/null +++ b/austinov.03.dealing_with_data/06_lkm2mpg.cpp @@ -0,0 +1,21 @@ +// lkm2mpg.cpp converts mpg to lp100km + +#include + +int main() +{ + unsigned int ui_lkm = 0; + + std::cout << "I can convert liters per 100 km into mpg." << std::endl; + std::cout << "Enter the consumption value to convert: "; + std::cin >> ui_lkm; + + const double MI_IN_100KM = 62.1371; + const double L_IN_GAL = 3.78541; + const double RATIO = MI_IN_100KM * L_IN_GAL; + + std::cout << ui_lkm << " liters per 100 km is around "; + std::cout << RATIO / ui_lkm << " mpg." << std::endl; + + return 0; +} From 988e8981fca71916497aa9979f4f52caa12eb700 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Wed, 6 Mar 2013 16:56:20 +0200 Subject: [PATCH 03/15] added *.out files --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 620d3dc..5c30c37 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,6 @@ *.lai *.la *.a + +# Compiled executables +*.out From 4953db146dd54aa57db3f2dcf1b480bcfd747a59 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Wed, 6 Mar 2013 18:29:09 +0200 Subject: [PATCH 04/15] Added ignore rules for VC generated trash --- .gitignore | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5c30c37..1188fd3 100644 --- a/.gitignore +++ b/.gitignore @@ -12,5 +12,24 @@ *.la *.a -# Compiled executables +# Compiled Executables +*.exe *.out + +# Archives +*.7z +*.zip + +# MSVC Generated Files +*.idb +*.ilk +*.log +*.obj +*.pdb +*.sdf +*.sln +*.suo +*.tlog +*.filters +*.vcxproj +*.lastbuildstate \ No newline at end of file From f44b66dc87063f857a91118c55dd63af8527c704 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Mon, 25 Mar 2013 00:06:41 +0200 Subject: [PATCH 05/15] Compound Types Assignments --- austinov.04.compound_types/01_namesages.cpp | 31 +++++++++++++++++++ austinov.04.compound_types/02_namesages.cpp | 31 +++++++++++++++++++ austinov.04.compound_types/03_lastfirst.cpp | 24 ++++++++++++++ .../04_strlastfirst.cpp | 20 ++++++++++++ austinov.04.compound_types/05_candybar.cpp | 13 ++++++++ austinov.04.compound_types/06_candybarr.cpp | 24 ++++++++++++++ austinov.04.compound_types/07_pizza.cpp | 19 ++++++++++++ austinov.04.compound_types/08_newpizza.cpp | 21 +++++++++++++ .../09_newcandybarr.cpp | 27 ++++++++++++++++ austinov.04.compound_types/10_40yddash.cpp | 20 ++++++++++++ 10 files changed, 230 insertions(+) create mode 100644 austinov.04.compound_types/01_namesages.cpp create mode 100644 austinov.04.compound_types/02_namesages.cpp create mode 100644 austinov.04.compound_types/03_lastfirst.cpp create mode 100644 austinov.04.compound_types/04_strlastfirst.cpp create mode 100644 austinov.04.compound_types/05_candybar.cpp create mode 100644 austinov.04.compound_types/06_candybarr.cpp create mode 100644 austinov.04.compound_types/07_pizza.cpp create mode 100644 austinov.04.compound_types/08_newpizza.cpp create mode 100644 austinov.04.compound_types/09_newcandybarr.cpp create mode 100644 austinov.04.compound_types/10_40yddash.cpp diff --git a/austinov.04.compound_types/01_namesages.cpp b/austinov.04.compound_types/01_namesages.cpp new file mode 100644 index 0000000..123eccf --- /dev/null +++ b/austinov.04.compound_types/01_namesages.cpp @@ -0,0 +1,31 @@ +// it asks for a name few times and stores that into array + +#include +#include + +int main() +{ + struct person + { + std::string fname; + std::string lname; + char grade; + short age; + }; + + person p0; + std::cout << "What is your first name? "; + getline(std::cin, p0.fname); + std::cout << "What is your last name? "; + getline(std::cin, p0.lname); + std::cout << "What letter grade do you deserve? "; + std::cin >> p0.grade; + std::cout << "What is your age? "; + std::cin >> p0.age; + + std::cout << "Name: " << p0.lname << ", " << p0.fname << std::endl; + std::cout << "Grade: " << static_cast(p0.grade + 1) << std::endl; + std::cout << "Age: " << p0.age << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/02_namesages.cpp b/austinov.04.compound_types/02_namesages.cpp new file mode 100644 index 0000000..123eccf --- /dev/null +++ b/austinov.04.compound_types/02_namesages.cpp @@ -0,0 +1,31 @@ +// it asks for a name few times and stores that into array + +#include +#include + +int main() +{ + struct person + { + std::string fname; + std::string lname; + char grade; + short age; + }; + + person p0; + std::cout << "What is your first name? "; + getline(std::cin, p0.fname); + std::cout << "What is your last name? "; + getline(std::cin, p0.lname); + std::cout << "What letter grade do you deserve? "; + std::cin >> p0.grade; + std::cout << "What is your age? "; + std::cin >> p0.age; + + std::cout << "Name: " << p0.lname << ", " << p0.fname << std::endl; + std::cout << "Grade: " << static_cast(p0.grade + 1) << std::endl; + std::cout << "Age: " << p0.age << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/03_lastfirst.cpp b/austinov.04.compound_types/03_lastfirst.cpp new file mode 100644 index 0000000..5ad2e01 --- /dev/null +++ b/austinov.04.compound_types/03_lastfirst.cpp @@ -0,0 +1,24 @@ +// it asks for a first and last name and then shows it comma separated + +#include +#include + +int main() +{ + char first [10] = {}; + char last [13] = {}; + + std::cout << "What is your first name? "; + std::cin.getline(first, 10); + std::cout << "What is your last name? "; + std::cin.getline(last, 13); + + char output [25] = {}; + strcat(output, last); + strcat(output, ", "); + strcat(output, first); + std::cout << "Here's the information in a single string: "; + std::cout << output << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/04_strlastfirst.cpp b/austinov.04.compound_types/04_strlastfirst.cpp new file mode 100644 index 0000000..3f95d75 --- /dev/null +++ b/austinov.04.compound_types/04_strlastfirst.cpp @@ -0,0 +1,20 @@ +// it asks for a first and last name and then shows it comma separated + +#include +#include + +int main() +{ + std::string first, last, output; + + std::cout << "What is your first name? "; + getline(std::cin, first); + std::cout << "What is your last name? "; + getline(std::cin, last); + + output = last + ", " + first; + std::cout << "Here's the information in a single string: "; + std::cout << output << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/05_candybar.cpp b/austinov.04.compound_types/05_candybar.cpp new file mode 100644 index 0000000..850c1a0 --- /dev/null +++ b/austinov.04.compound_types/05_candybar.cpp @@ -0,0 +1,13 @@ +// candybar.cpp declares the structure and populates an instance + +#include +#include + +int main() +{ + struct candybar {std::string n; float w; int c;}; + candybar snack = {"Mocha Munch", 2.3, 350}; + std::cout << snack.n << ", " << snack.w << ", " << snack.c << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/06_candybarr.cpp b/austinov.04.compound_types/06_candybarr.cpp new file mode 100644 index 0000000..dd35274 --- /dev/null +++ b/austinov.04.compound_types/06_candybarr.cpp @@ -0,0 +1,24 @@ +// candybar.cpp declares the structure and populates an instance + +#include +#include + +int main() +{ + struct candybar {std::string n; float w; int c;}; + candybar cba [3]; + cba[0].n = "Candy Bar 0"; + cba[0].w = 0.9; + cba[0].c = 210; + std::cout << cba[0].n << ", " << cba[0].w << ", " << cba[0].c << std::endl; + cba[1].n = "Candy Bar 1"; + cba[1].w = 1.9; + cba[1].c = 321; + std::cout << cba[1].n << ", " << cba[1].w << ", " << cba[1].c << std::endl; + cba[2].n = "Candy Bar 2"; + cba[2].w = 2.9; + cba[2].c = 432; + std::cout << cba[2].n << ", " << cba[2].w << ", " << cba[2].c << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/07_pizza.cpp b/austinov.04.compound_types/07_pizza.cpp new file mode 100644 index 0000000..3085686 --- /dev/null +++ b/austinov.04.compound_types/07_pizza.cpp @@ -0,0 +1,19 @@ +// pizza.cpp introduces a pizzacompany structure and populates one instance + +# include +# include + +int main() +{ + struct pizza_company {std::string name; int d; float w;} pizza; + std::cout << "Please specify a company: "; + getline(std::cin, pizza.name); + std::cout << "Please enter the diameter in mm: "; + std::cin >> pizza.d; + std::cout << "Please specify weight in kg: "; + std::cin >> pizza.w; + std::cout << std::endl << "You have entered: "; + std::cout << pizza.name << ", " << pizza.d << ", " << pizza.w << std::endl; + + return 0; +} diff --git a/austinov.04.compound_types/08_newpizza.cpp b/austinov.04.compound_types/08_newpizza.cpp new file mode 100644 index 0000000..2457006 --- /dev/null +++ b/austinov.04.compound_types/08_newpizza.cpp @@ -0,0 +1,21 @@ +// pizza.cpp uses new to allocate the structure + +# include +# include + +int main() +{ + struct pizza_company {std::string name; int d; float w;}; + pizza_company* p_pizza = new pizza_company; + std::cout << "Please specify a company: "; + getline(std::cin, p_pizza->name); + std::cout << "Please enter the diameter in mm: "; + std::cin >> p_pizza->d; + std::cout << "Please specify weight in kg: "; + std::cin >> p_pizza->w; + std::cout << std::endl << "You have entered: "; + std::cout << p_pizza->name << ", " << p_pizza->d << ", " << p_pizza->w; + std::cout << std::endl; + + return 0; +} diff --git a/austinov.04.compound_types/09_newcandybarr.cpp b/austinov.04.compound_types/09_newcandybarr.cpp new file mode 100644 index 0000000..0484ad8 --- /dev/null +++ b/austinov.04.compound_types/09_newcandybarr.cpp @@ -0,0 +1,27 @@ +// candybar.cpp declares the structure and populates an instance + +# include +# include + +int main() +{ + struct candybar {std::string n; float w; int c;}; + candybar * p_cba = new candybar[3]; + p_cba[0].n = "Candy Bar 0"; + p_cba[0].w = 0.9; + p_cba[0].c = 210; + std::cout << p_cba[0].n << ", " << p_cba[0].w << ", " << p_cba[0].c ; + std::cout << std::endl; + p_cba[1].n = "Candy Bar 1"; + p_cba[1].w = 1.9; + p_cba[1].c = 321; + std::cout << p_cba[1].n << ", " << p_cba[1].w << ", " << p_cba[1].c ; + std::cout << std::endl; + p_cba[2].n = "Candy Bar 2"; + p_cba[2].w = 2.9; + p_cba[2].c = 432; + std::cout << p_cba[2].n << ", " << p_cba[2].w << ", " << p_cba[2].c ; + std::cout << std::endl; + + return 0; +}; diff --git a/austinov.04.compound_types/10_40yddash.cpp b/austinov.04.compound_types/10_40yddash.cpp new file mode 100644 index 0000000..7def011 --- /dev/null +++ b/austinov.04.compound_types/10_40yddash.cpp @@ -0,0 +1,20 @@ +// 40yddash.cpp asks for the sprint times and shows the average + +# include +# include + +int main() +{ + std::array lap_times; + float time_sum = 0.0; + for (int i = 0; (i < lap_times.max_size()); i++) + { + std::cout << "Please enter the result in seconds: "; + std::cin >> lap_times[i]; + time_sum += lap_times[i]; + }; + std::cout << "The average time is: " << time_sum / lap_times.size(); + std::cout << std::endl; + + return 0; +}; From efb0d7e383f274c3e81bae94e820110119a255da Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Mon, 25 Mar 2013 11:04:39 +0200 Subject: [PATCH 06/15] chapter five task one --- .../01_intsum.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 austinov.05.loops_and_relational_expressions/01_intsum.cpp diff --git a/austinov.05.loops_and_relational_expressions/01_intsum.cpp b/austinov.05.loops_and_relational_expressions/01_intsum.cpp new file mode 100644 index 0000000..9896a97 --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/01_intsum.cpp @@ -0,0 +1,20 @@ +// intsum.cpp calculatest the sum between two integers specified + +# include + +int main() +{ + int start, stop, sum = 0; + std::cout << "Please enter the lower int: "; + std::cin >> start; + std::cout << "Please specify the higher one: "; + std::cin >> stop; + for ( int i = start; i <= stop; i++ ) + { + sum += i; + } + std::cout << "The sum of ints from " << start << " to " << stop; + std::cout << " is " << sum << std::endl; + + return 0; +}; From c286b7cc07cb3a6f418c8fba031acd04356162c2 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 9 Apr 2013 20:30:25 +0300 Subject: [PATCH 07/15] Chapter 5 Assignments --- .../02_intsum.cpp | 22 ++++++++++++++ .../03_cumsum.cpp | 16 ++++++++++ .../04_invest.cpp | 18 ++++++++++++ .../05_sales.cpp | 23 +++++++++++++++ .../06_3ysales.cpp | 29 +++++++++++++++++++ .../07_carcat.cpp | 29 +++++++++++++++++++ .../08_wordloop.cpp | 19 ++++++++++++ .../09_strloop.cpp | 19 ++++++++++++ .../10_asterisks.cpp | 17 +++++++++++ 9 files changed, 192 insertions(+) create mode 100644 austinov.05.loops_and_relational_expressions/02_intsum.cpp create mode 100644 austinov.05.loops_and_relational_expressions/03_cumsum.cpp create mode 100644 austinov.05.loops_and_relational_expressions/04_invest.cpp create mode 100644 austinov.05.loops_and_relational_expressions/05_sales.cpp create mode 100644 austinov.05.loops_and_relational_expressions/06_3ysales.cpp create mode 100644 austinov.05.loops_and_relational_expressions/07_carcat.cpp create mode 100644 austinov.05.loops_and_relational_expressions/08_wordloop.cpp create mode 100644 austinov.05.loops_and_relational_expressions/09_strloop.cpp create mode 100644 austinov.05.loops_and_relational_expressions/10_asterisks.cpp diff --git a/austinov.05.loops_and_relational_expressions/02_intsum.cpp b/austinov.05.loops_and_relational_expressions/02_intsum.cpp new file mode 100644 index 0000000..277f21b --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/02_intsum.cpp @@ -0,0 +1,22 @@ +// factorials.cpp calculate the first 16 factorials + +# include +# include + +const int ARR_LEN = 100; + +int main() +{ + long double factorials[ARR_LEN]; + factorials[0] = 1; + for ( int i = 1; i < ARR_LEN; i++ ) + { + factorials[i] = i * factorials[i-1]; + } + // std::cout << std::fixed; + for ( int i = 0; i < ARR_LEN; i++ ) + { + std::cout << i << "! = " << factorials[i] << std::endl; + } + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/03_cumsum.cpp b/austinov.05.loops_and_relational_expressions/03_cumsum.cpp new file mode 100644 index 0000000..49bfb0f --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/03_cumsum.cpp @@ -0,0 +1,16 @@ +// cumsum.cpp asks you to enter the nums and calculates the sum to date + +# include + +int main() +{ + int n = 0; + long sum = 0; + do { + std::cout << "Please enter the integer: "; + std::cin >> n; + std::cout << "The sum of entred numbers is: " << (sum += n); + std::cout << std::endl << std::endl; + } while (n != 0); + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/04_invest.cpp b/austinov.05.loops_and_relational_expressions/04_invest.cpp new file mode 100644 index 0000000..d0a13f5 --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/04_invest.cpp @@ -0,0 +1,18 @@ +// invest.cpp compares the simple and compound investments + +# include + +int main() +{ + double bal0, bal1; + bal0 = bal1 = 100; + int years = 0; + do { + bal0 += 0.1 * 100; + bal1 += 0.05 * bal1; + years++; + } while (bal0 > bal1); + std::cout << "It took " << years << " years so that "; + std::cout << bal1 << " is now more than " << bal0 << std::endl; + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/05_sales.cpp b/austinov.05.loops_and_relational_expressions/05_sales.cpp new file mode 100644 index 0000000..c319bc8 --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/05_sales.cpp @@ -0,0 +1,23 @@ +// sales.cpp counts the yearly worth from monthly sales + +# include +# include +# include + +int main() +{ + const std::array Months = {"Jan", "Feb", "Mar", "Apr", + "May", "Jun", "Jul", "Aug", + "Sep", "Oct", "Nov", "Dec"}; + std::array sales; + int yearly_sales = 0; + + for (int i = 0; i < Months.size(); i++) { + std::cout << "Please enter the sales for " << Months[i] << std::endl; + std::cin >> sales[i]; + yearly_sales += sales[i]; + }; + + std::cout << "Yearly sales worth " << yearly_sales << " pcs." << std::endl; + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/06_3ysales.cpp b/austinov.05.loops_and_relational_expressions/06_3ysales.cpp new file mode 100644 index 0000000..c0f1598 --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/06_3ysales.cpp @@ -0,0 +1,29 @@ +// sales.cpp counts the yearly worth from monthly sales + +# include +# include +# include + +int main() +{ + int total_sales = 0; + const std::array Months = {"Jan", "Feb", "Mar", "Apr", + "May", "Jun", "Jul", "Aug", + "Sep", "Oct", "Nov", "Dec"}; + std::array, 3> sales; + for (int y = 0; y < sales.size(); y++) { + int yearly_sales = 0; + for (int i = 0; i < Months.size(); i++) { + std::cout << "Please enter the sales for " << Months[i]; + std::cout << " of year " << (y + 1) << std::endl; + std::cin >> sales[y][i]; + yearly_sales += sales[y][i]; + }; + std::cout << "Yearly sales for year " << y << " worth " << yearly_sales; + std::cout << " pcs." << std::endl; + total_sales += yearly_sales; + }; + + std::cout << "Total sales worth " << total_sales << " pcs." << std::endl; + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/07_carcat.cpp b/austinov.05.loops_and_relational_expressions/07_carcat.cpp new file mode 100644 index 0000000..5e4a74f --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/07_carcat.cpp @@ -0,0 +1,29 @@ +// carcat.cpp makes a cars catalog and displays them + +# include +# include +# include + +int main() +{ + int cars = 0; + struct car {std::string make; int year;}; + std::cout << "How many cars do you want to catalog?"; + std::cin >> cars; + car * catalog = new car[cars]; + for (int i = 0; i < cars; i++) + { + std::cout << "Car #" << i << std::endl; + std::cout << "Please enter a make: "; + std::cin >> catalog[i].make; + std::cout << "Please enter the year made: "; + std::cin >> catalog[i].year; + }; + std::cout << "Here's your collection: " << std::endl; + for (int i = 0; i < cars; i++) + { + std::cout << catalog[i].make << ' ' << catalog[i].year << std::endl; + }; + delete [] catalog; + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/08_wordloop.cpp b/austinov.05.loops_and_relational_expressions/08_wordloop.cpp new file mode 100644 index 0000000..f83eb63 --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/08_wordloop.cpp @@ -0,0 +1,19 @@ +// wordloop.cpp counts the words until 'done' word is entered + +# include +# include + +int main() +{ + int words = 0; + char word[80] = {}; + std::cout << "I'll count the words, so you'd better type them."; + std::cout << " Enter 'done' to stop." << std::endl; + while (strcmp(word, "done") != 0) + { + std::cin >> word; + words++; + } + std::cout << "\nYou've entered " << (words - 1) << " words." << std::endl; + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/09_strloop.cpp b/austinov.05.loops_and_relational_expressions/09_strloop.cpp new file mode 100644 index 0000000..1424c58 --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/09_strloop.cpp @@ -0,0 +1,19 @@ +// wordloop.cpp counts the words until 'done' word is entered + +# include +# include + +int main() +{ + int words = 0; + std::string word = {}; + std::cout << "I'll count the words, so you'd better type them."; + std::cout << " Enter 'done' to stop." << std::endl; + while (word != "done") + { + std::cin >> word; + words++; + } + std::cout << "\nYou've entered " << (words - 1) << " words." << std::endl; + return 0; +}; diff --git a/austinov.05.loops_and_relational_expressions/10_asterisks.cpp b/austinov.05.loops_and_relational_expressions/10_asterisks.cpp new file mode 100644 index 0000000..11a721d --- /dev/null +++ b/austinov.05.loops_and_relational_expressions/10_asterisks.cpp @@ -0,0 +1,17 @@ +// asterisks.cpp will display n rows of growing number of asterisks + +# include +# include + +int main() +{ + char dot = '.'; + char star = '*'; + int d, s, rows = 0; + std::cout << "Please enter the number of rows to draw: "; + std::cin >> rows; std::cout << std::endl; + for (d = rows - 1, s = 1; d >= 0; --d, ++s) + std::cout << std::string(d, dot) << std::string(s, star) << std::endl; + std::cout << std::endl; + return 0; +}; From 59928380ceb1d393a3318736ef7e83a2cb692250 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 9 Apr 2013 20:37:46 +0300 Subject: [PATCH 08/15] added opensdf to ignore list --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 1188fd3..fe0ca23 100644 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,6 @@ *.suo *.tlog *.filters +*.opensdf *.vcxproj -*.lastbuildstate \ No newline at end of file +*.lastbuildstate From 0f4b7bd84c97266dc76700e47277f389554cc888 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Wed, 19 Jun 2013 15:36:43 +0300 Subject: [PATCH 09/15] Chapter 6 Assignments --- .../01.nodigits.cpp | 30 ++++ .../02.donations.cpp | 47 ++++++ .../03.menu.cpp | 90 +++++++++++ .../04.bop.cpp | 148 ++++++++++++++++++ .../05.tvarps.cpp | 59 +++++++ .../06.patrons.cpp | 95 +++++++++++ .../07.vowels.cpp | 64 ++++++++ .../08.readfile.cpp | 43 +++++ .../09.patrons.cpp | 95 +++++++++++ .../patrons.cfg | 9 ++ 10 files changed, 680 insertions(+) create mode 100644 austinov.06.branching_statements_and_logical_operators/01.nodigits.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/02.donations.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/03.menu.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/04.bop.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/05.tvarps.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/06.patrons.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/07.vowels.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/08.readfile.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/09.patrons.cpp create mode 100644 austinov.06.branching_statements_and_logical_operators/patrons.cfg diff --git a/austinov.06.branching_statements_and_logical_operators/01.nodigits.cpp b/austinov.06.branching_statements_and_logical_operators/01.nodigits.cpp new file mode 100644 index 0000000..42d8bad --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/01.nodigits.cpp @@ -0,0 +1,30 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write aprogram that reads keyboard input to the @ symbol */ +/* and than echoes the input except for digits, converting */ +/* each uppercase character to lowercase, and vice versa. */ +/* (Don’t forget the cctypefamily.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include + +int main() +{ + char ch; + std::cout << "HINT: This app quits as you enter '@'\n"; + std::cout << "Please feel free to enter whatever you want\n"; + while ('@' != (ch = std::cin.get())) + { + if (std::isdigit(ch)) continue; + if (std::islower(ch)) + ch = std::toupper(ch); + else + if (std::isupper(ch)) + ch = std::tolower(ch); + std::cout << ch; + }; + return 0; +}; + diff --git a/austinov.06.branching_statements_and_logical_operators/02.donations.cpp b/austinov.06.branching_statements_and_logical_operators/02.donations.cpp new file mode 100644 index 0000000..6d38926 --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/02.donations.cpp @@ -0,0 +1,47 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that reads up to 10 donation values into an array */ +/* of double. (Or, if you prefer, use an array template object.) The */ +/* program should terminate input on non-numeric input. */ +/* It should report the average of the numbers and also report how */ +/* many numbers in the array are larger than the average. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include + +int main() +{ + double sum = 0; + double average = 0; + double element = 0; + unsigned long i = 0; + // the initialization below may be not compatible with C++98 + std::array donations {}; + + std::cout << "Please enter up to 10 donations:" << std::endl;; + for (i = 0; i < donations.max_size(); i++) { + if (!(std::cin >> element)) { + std::cout << "Non-numeric entered. Terminating input.\n"; + break; + }; + donations[i] = element; + sum += element; + }; + + if (i > 0) + { + average = sum / donations.size(); + std::cout << "The average donation is " << average << std::endl; + for (i = 0; i < donations.size(); i++) { + if (donations[i] > average) + std::cout << "\nDonation " << donations[i] << " > average"; + }; + } else std::cout << "Program requires at least one donation."; + std::cout << std::endl; + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/03.menu.cpp b/austinov.06.branching_statements_and_logical_operators/03.menu.cpp new file mode 100644 index 0000000..6902926 --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/03.menu.cpp @@ -0,0 +1,90 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a precursor to a menu-driven program. The program should */ +/* display a menu offering four choices, each labeled with a letter. */ +/* If the user responds with a letter other than one of the four */ +/* valid choices, the program should prompt the user to enter a */ +/* valid response until the user complies. Then the program should */ +/* use a switch to select a simple action based on the user’s */ +/* selection. A program run could look something like this: */ +/* */ +/* Please enter one of the following choices: */ +/* c) carnivore p) pianist */ +/* t) tree g) game */ +/* f */ +/* Please enter a c, p, t, or g: q */ +/* Please enter a c, p, t, or g: t */ +/* A maple is a tree. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +void showmenu(void); +void carnivore(void); +void pianist(void); +void tree(void); +void game(void); + +void showmenu() +{ + std::cout << "Please enter one of the following choises:" + << std::endl << "c) carnivore p) pianist" + << std::endl << "t) tree g) game" << std::endl; +} + +void carnivore() +{ + std::cout << "WTF the carnivore is???" << std::endl; +} + +void pianist() +{ + std::cout << "Rakhmaninov was a pianist, wasn't he?" << std::endl; +} + +void game() +{ + std::cout << "Super Mario is an epic game, am I right?" << std::endl; +} + +void tree() +{ + std::cout << "Oak tree is the strongest one, agree?" << std::endl; +} + + +int main() +{ + bool repeat; + char choice; + + showmenu(); + do { + repeat = false; + std::cin >> choice; + + switch (choice) + { + case 'c' : + case 'C' : carnivore(); + break; + case 'p' : + case 'P' : pianist(); + break; + case 'g' : + case 'G' : game(); + break; + case 't' : + case 'T' : tree(); + break; + + default: repeat = true; + std::cout << "\nPlease make a choice from 'c, p, g, t': "; + }; + + } while (repeat); + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/04.bop.cpp b/austinov.06.branching_statements_and_logical_operators/04.bop.cpp new file mode 100644 index 0000000..e40c414 --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/04.bop.cpp @@ -0,0 +1,148 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* When you join the Benevolent Order of Programmers (BOP), you can */ +/* be known at BOP meetings by your real name, your job title, or */ +/* your secret BOP name. Write a program that can list members by */ +/* real name, by job title, by secret name or by a mem-ber’s */ +/* preference. Base the program on the following structure: */ +/* */ +/* // Benevolent Order of Programmers name structure */ +/* struct bop { */ +/* char fullname[strsize]; // real name */ +/* char title[strsize]; // job title */ +/* char bopname[strsize]; // secret BOP name */ +/* int preference; // 0 = fullname, 1 = title, 2 = bopname */ +/* }; */ +/* */ +/* In the program, create a small array of such structures and */ +/* initialize it to suitable values. Have the program run a loop */ +/* that lets the user select from different alternatives: */ +/* a. display by name b. display by title */ +/* c. display by bopname d. display by preference */ +/* q. quit */ +/* */ +/* Note that “display by preference” does not mean display the */ +/* preference member; it means display the member corresponding to */ +/* the preference number. For instance, if preference is 1, choice d */ +/* would display the programmer’s job title. */ +/* */ +/* A sample run may look something like the following: */ +/* */ +/* Benevolent Order of Programmers Report */ +/* a. display by name b. display by title */ +/* c. display by bopname d. display by preference */ +/* q. quit */ +/* Enter your choice: a */ +/* Wimp Macho */ +/* Raki Rhodes */ +/* Celia Laiter */ +/* Hoppy Hipman */ +/* Pat Hand */ +/* Next choice: d */ +/* Wimp Macho */ +/* Junior Programmer */ +/* MIPS */ +/* Analyst Trainee */ +/* LOOPY */ +/* Next choice: q */ +/* Bye! */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include + +/* Benevolent Order of Programmers name structure */ +struct bop { + char fullname[12]; /* real name */ + char title[12]; /* job title */ + char bopname[12]; /* secret BOP name */ + unsigned int preference; /* 0 = fullname, 1 = title, 2 = bopname */ +}; + +enum {by_name, by_title, by_bop, by_pref}; + +void showmenu(void); +void display(const bop * p_member, unsigned int by); +void list(const bop p_array_of_bop[], unsigned int len, unsigned int by); + +void showmenu() +{ + std::cout << "Benevolent Order of Programmers Report" << std::endl + << "a. display by name b. display by title" << std::endl + << "c. display by bopname d. display by preference" << std::endl + << "q. quit" << std::endl << "Enter your choice:"; +} + +void display(const bop * p_member, unsigned int by) +{ + switch (by) + { + case by_name: + std::cout << p_member->fullname << std::endl; + break; + case by_title: + std::cout << p_member->title << std::endl; + break; + case by_bop: + std::cout << p_member->bopname << std::endl; + }; +} + +void list(const bop p_array_of_bop[], unsigned int len, unsigned int by) +{ + bop member; + for (unsigned int i = 0; i < len; i++) + { + member = p_array_of_bop[i]; + if (by == by_pref) + display(&member, member.preference); + else + display(&member, by); + }; +} + + +int main() +{ + const std::array members = { + { + {"Real Name 0", "Job Title 0", "BOP Name 0", 0}, + {"Real Name 1", "Job Title 1", "BOP Name 1", 1}, + {"Real Name 2", "Job Title 2", "BOP Name 2", 2} + } + }; + + char choice; + unsigned int len = members.size(); + + showmenu(); + + std::cin >> choice; + while (choice != 'q') + { + switch (choice) + { + case 'a' : + case 'A' : list(members.data(), len, by_name); + break; + case 'b' : + case 'B' : list(members.data(), len, by_title); + break; + case 'c' : + case 'C' : list(members.data(), len, by_bop); + break; + case 'd' : + case 'D' : list(members.data(), len, by_pref); + break; + + default: std::cout << "No such option: " << choice; + }; + std::cout << "\nNext Choice: "; + std::cin >> choice; + }; + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/05.tvarps.cpp b/austinov.06.branching_statements_and_logical_operators/05.tvarps.cpp new file mode 100644 index 0000000..e6d6aa8 --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/05.tvarps.cpp @@ -0,0 +1,59 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* The Kingdom of Neutronia, where the unit of currency is the tvarp */ +/* has the following income tax code: */ +/* */ +/* First 5,000 tvarps: 0% tax */ +/* Next 10,000 tvarps: 10% tax */ +/* Next 20,000 tvarps:15% tax */ +/* Tvarps after 35,000:20% tax */ +/* */ +/* For example, someone earning 38,000 tvarps would owe */ +/* 5000*0.00 + 10000*0.10 + 20000*0.15 + 3000*0.20, or 4,600 tvarps. */ +/* */ +/* Write a program that uses a loop to solicit incomes and to report */ +/* tax owed. The loop should terminate when the user enters a */ +/* negative number or non-numeric input. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +int main() +{ + const double T05K = 5000; + const double T10K = 10000; + const double T20K = 20000; + double income; + double tax; + + std::cout << "Please specify the income: "; + while (std::cin >> income) + { + tax = 0.0; + if (income - T05K > 0.0) + { + income -= T05K; + + if (income - T10K > 0.0) + { + income -= T10K; + tax += T10K * 0.1; + + if (income - T20K > 0.0) + { + income -= T20K; + tax += T20K * 0.15 + income * 0.2; + } + else + tax += income * 0.15; + } + else + tax += income * 0.1; + }; + std::cout << std::endl << "The tax owed is " << tax << std::endl; + }; + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/06.patrons.cpp b/austinov.06.branching_statements_and_logical_operators/06.patrons.cpp new file mode 100644 index 0000000..a68debb --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/06.patrons.cpp @@ -0,0 +1,95 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Put together a program that keeps track of monetary contributions */ +/* to the Society for the Preservation of Rightful Influence. */ +/* */ +/* It should ask the user to enter the number of contributors and */ +/* then solicit the user to enter the name and contribution of each */ +/* contributor. */ +/* */ +/* The information should be stored in a dynamically allocated array */ +/* of structures. Each structure should have two members:a character */ +/* array (or else a string object) to store the name and a double */ +/* member to hold the amount of the contribution. After reading all */ +/* the data, the program should display the names and amounts */ +/* donated for all donors who contributed $10,000 or more. This list */ +/* should be headed by the label Grand Patrons. After that, the */ +/* program should list the remaining donors. That list should be */ +/* headed Patrons. If there are no donors in one of the categories, */ +/* the program should print the word “none.” Aside from displaying */ +/* two categories, the program need do no sorting. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include + +struct Donor { + std::string name; + double donation; +}; + +typedef Donor * T_P2Donor; + +void show_donor(T_P2Donor contributor); + +void show_donor(T_P2Donor contributor) +{ + std::cout << contributor->name << ' ' + << contributor->donation << std::endl; +} + +int main() +{ + + size_t ar_sz = 0; + std::string var_name; + double var_donation = 0; + + std::cout << "Please enter the number of contributors: "; + std::cin >> ar_sz; + + T_P2Donor * p_donors = new T_P2Donor[ar_sz]; + + for (unsigned int i = 0; i < ar_sz; i++) + { + std::cout << std::endl << "Please enter the name: "; + std::cin.ignore(std::numeric_limits::max(), '\n'); + std::getline(std::cin, var_name); + + std::cout << std::endl << "Please enter the amount of donation: "; + std::cin >> var_donation ; + + p_donors[i] = new Donor; + p_donors[i]->name = var_name; + p_donors[i]->donation = var_donation; + + }; + + for (unsigned int grp = 0; grp < 2; grp++) + { + std::cout << std::endl + << ((0 == grp) ? "Grand Patrons" : "Patrons") + << std::endl; + for (unsigned int i = 0; i < ar_sz; i++) + { + if (0 == grp && p_donors[i]->donation > 9999) + show_donor(p_donors[i]); + else + if (1 == grp) + { + if (p_donors[i]->donation < 10000) + show_donor(p_donors[i]); + // free memory on the second turn + delete p_donors[i]; + }; + }; + }; + std::cout << std::endl; + + delete [] p_donors; + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/07.vowels.cpp b/austinov.06.branching_statements_and_logical_operators/07.vowels.cpp new file mode 100644 index 0000000..507f85e --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/07.vowels.cpp @@ -0,0 +1,64 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that reads input a word at a time until a lone q */ +/* is entered. The program should then report the number of words */ +/* that began with vowels, the number that began with consonants, */ +/* and the number that fit neither of those categories. */ +/* */ +/* One approach is to use isalpha() to discriminate between words */ +/* beginning with letters and those that don’t and then use an if */ +/* or switch statement to further identify those passing the */ +/* isalpha() test that begin with vowels. */ +/* A sample run might look like this: */ +/* */ +/* Enter words (q to quit): */ +/* The 12 awesome oxen ambled */ +/* quietly across 15 meters of lawn. q */ +/* 5 words beginning with vowels */ +/* 4 words beginning with consonants */ +/* 2 others */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include + +bool is_vowel(char ch); +bool is_vowel(char ch) +{ + bool vowel = false; + switch (ch) { + case 'a': case 'A': + case 'o': case 'O': + case 'e': case 'E': + case 'u': case 'U': + case 'i': case 'I': vowel = true; + break; + }; + return vowel; +} + +int main() +{ + std::string word; + unsigned int vow = 0; + unsigned int con = 0; + unsigned int oth = 0; + + std::cout << "Enter the words (q to quit): " << std::endl; + while (std::cin >> word && !("q" == word || "Q" == word)) + { + if (isalpha(word[0])) + { + (is_vowel(word[0])) ? vow++ : con++; + } else oth++; + }; + std::cout << vow << " words beginning with vowels" << std::endl; + std::cout << con << " words beginning with consonants" << std::endl; + std::cout << oth << " others" << std::endl; + + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/08.readfile.cpp b/austinov.06.branching_statements_and_logical_operators/08.readfile.cpp new file mode 100644 index 0000000..488f7e0 --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/08.readfile.cpp @@ -0,0 +1,43 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that opens a text file, reads it */ +/* character-by-character to the end of the file, */ +/* and reports the number of characters in the file. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include +# include + + +int main() +{ + bool code = 0; + std::string filename; + std::ifstream textfile; + unsigned int total = 0; + + std::cout << "Enter the filename: " << std::endl; + std::cin >> filename; + textfile.open(filename); + if (textfile.is_open()) + { + while (textfile.good()) { + textfile.get(); + total++; + }; + textfile.close(); + std::cout << "There're total " << total + << " characters in file " << filename << std::endl; + } + else + { + std::cout << "The file " << filename << " not found"; + code = 1; + }; + + return code; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/09.patrons.cpp b/austinov.06.branching_statements_and_logical_operators/09.patrons.cpp new file mode 100644 index 0000000..7c6548c --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/09.patrons.cpp @@ -0,0 +1,95 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Programming Exercise 6 but modify it to get information from a */ +/* file. The first item in the file should be the number of */ +/* contributors, and the rest of the file should consist of pairs of */ +/* lines, with the first line of each pair being a contributor’s */ +/* name and the second line being a contribution. That is, the file */ +/* should look like this: */ +/* */ +/* 4 */ +/* Sam Stone */ +/* 2000 */ +/* Freida Flass */ +/* 100500 */ +/* Tammy Tubbs */ +/* 5000 */ +/* Rich Raptor */ +/* 55000 */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include +# include + +struct Donor { + std::string name; + double donation; +}; + +typedef Donor * T_P2Donor; + +void show_donor(T_P2Donor contributor); + +void show_donor(T_P2Donor contributor) +{ + std::cout << contributor->name << ' ' + << contributor->donation << std::endl; +} + +int main() +{ + + size_t ar_sz = 0; + std::string var_name; + double var_donation = 0; + + std::ifstream configfile; + configfile.open("patrons.cfg"); + configfile >> ar_sz; + //std::cout << "ar_sz" << ar_sz; + + T_P2Donor * p_donors = new T_P2Donor[ar_sz]; + + for (unsigned int i = 0; i < ar_sz; i++) + { + // this is very important for making the getline read properly + configfile.ignore(std::numeric_limits::max(), '\n'); + std::getline(configfile, var_name); + configfile >> var_donation ; + //std::cout << "name" << var_name << "donation" << var_donation; + + p_donors[i] = new Donor; + p_donors[i]->name = var_name; + p_donors[i]->donation = var_donation; + + }; + + for (unsigned int grp = 0; grp < 2; grp++) + { + std::cout << std::endl + << ((0 == grp) ? "Grand Patrons" : "Patrons") + << std::endl; + for (unsigned int i = 0; i < ar_sz; i++) + { + if (0 == grp && p_donors[i]->donation > 9999) + show_donor(p_donors[i]); + else + if (1 == grp) + { + if (p_donors[i]->donation < 10000) + show_donor(p_donors[i]); + // free memory on the second turn + delete p_donors[i]; + }; + }; + }; + std::cout << std::endl; + + delete [] p_donors; + + return 0; +} + diff --git a/austinov.06.branching_statements_and_logical_operators/patrons.cfg b/austinov.06.branching_statements_and_logical_operators/patrons.cfg new file mode 100644 index 0000000..90e6fba --- /dev/null +++ b/austinov.06.branching_statements_and_logical_operators/patrons.cfg @@ -0,0 +1,9 @@ +4 +Sam Stone +2000 +Freida Flass +100500 +Tammy Tubbs +5000 +Rich Raptor +55000 From c258fa4712462820f45105dda2eaadb976b9c775 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 25 Jun 2013 10:51:48 +0300 Subject: [PATCH 10/15] Chapter 7 and Chapter 8 Assignments --- .../01.hmean.cpp | 35 +++++++ .../02.golf.cpp | 50 ++++++++++ .../03.box.cpp | 66 +++++++++++++ .../04.lottery.cpp | 45 +++++++++ .../05.factorial.cpp | 30 ++++++ .../06.reverse.cpp | 69 +++++++++++++ .../07.range.cpp | 83 ++++++++++++++++ .../08.a.cpp | 55 +++++++++++ .../08.b.cpp | 56 +++++++++++ .../09.astruct.cpp | 97 +++++++++++++++++++ .../01.printn.cpp | 51 ++++++++++ .../02.cdbar.cpp | 57 +++++++++++ .../03.upper.cpp | 49 ++++++++++ .../04.skel.cpp | 94 ++++++++++++++++++ .../05.max5.cpp | 32 ++++++ .../05.maxn.cpp | 46 +++++++++ .../06.sumarr.cpp | 59 +++++++++++ 17 files changed, 974 insertions(+) create mode 100644 austinov.07.functions_cpp_programming_modules/01.hmean.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/02.golf.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/03.box.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/04.lottery.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/05.factorial.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/06.reverse.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/07.range.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/08.a.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/08.b.cpp create mode 100644 austinov.07.functions_cpp_programming_modules/09.astruct.cpp create mode 100644 austinov.08.adventures_in_functions/01.printn.cpp create mode 100644 austinov.08.adventures_in_functions/02.cdbar.cpp create mode 100644 austinov.08.adventures_in_functions/03.upper.cpp create mode 100644 austinov.08.adventures_in_functions/04.skel.cpp create mode 100644 austinov.08.adventures_in_functions/05.max5.cpp create mode 100644 austinov.08.adventures_in_functions/05.maxn.cpp create mode 100644 austinov.08.adventures_in_functions/06.sumarr.cpp diff --git a/austinov.07.functions_cpp_programming_modules/01.hmean.cpp b/austinov.07.functions_cpp_programming_modules/01.hmean.cpp new file mode 100644 index 0000000..eb88dae --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/01.hmean.cpp @@ -0,0 +1,35 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that repeatedly asks the user to enter pairs of */ +/* numbers until at least one of the pair is 0. For each pair, the */ +/* program should use a function to calculate the harmonic mean of */ +/* the numbers. The function should return the answer to main(), */ +/* which should report the result. The harmonic mean of the numbers */ +/* is the inverse of the average of the inverses and can be */ +/* calculated as follows: */ +/* */ +/* harmonic mean = 2.0 * x * y / (x + y) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +double hmean(double, double); + +double hmean(double x, double y) +{ + return 2.0 * x * y / (x + y); +} + +int main() +{ + double x, y; + std::cout << "Please enter a pair of numbers: "; + while ((std::cin >> x >> y) && !(0.0 == x || 0.0 == y)) + { + std::cout << "The harmonic mean is " << hmean(x, y); + std::cout << std::endl << "Please enter a pair of numbers: "; + }; + + return 0; +} diff --git a/austinov.07.functions_cpp_programming_modules/02.golf.cpp b/austinov.07.functions_cpp_programming_modules/02.golf.cpp new file mode 100644 index 0000000..a30be6f --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/02.golf.cpp @@ -0,0 +1,50 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that asks the user to enter up to 10 golf scores, */ +/* which are to be stored in an array. You should provide a means */ +/* for the user to terminate input prior to entering 10 scores. */ +/* The program should display all the scores on one line and report */ +/* the average score. Handle input, display and the average */ +/* calculation with three separate array-processing functions. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +const unsigned int MAX_SIZE = 10; + +unsigned int input(int []); +void display(const int [], unsigned int); +double average(const int [], unsigned int); + +unsigned int +input(int arr[]) +{ + unsigned int i = 0; + std::cout << "Please enter up to " << MAX_SIZE << " golf scores: "; + while (std::cin >> arr[i] && i < MAX_SIZE) i++; + return i; +} + +void display(const int arr[], unsigned int sz) +{ + for (unsigned int i = 0; i < sz; i++) std::cout << " " << arr[i]; +} + +double average(const int arr[], unsigned int sz) +{ + int sum = 0; + unsigned int i; + for (i = 0; i < sz; i++) sum += arr[i]; + return sum / ++i; +} + +int main() +{ + int scores[MAX_SIZE]; + unsigned int size = input(scores); + display(scores, size); + std::cout << std::endl << "Average score is " + << average(scores, size) << std::endl; + return 0; +} diff --git a/austinov.07.functions_cpp_programming_modules/03.box.cpp b/austinov.07.functions_cpp_programming_modules/03.box.cpp new file mode 100644 index 0000000..85a1a75 --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/03.box.cpp @@ -0,0 +1,66 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a structure declaration: */ +/* */ +/* structure box { */ +/* char maker[40]; */ +/* float height; */ +/* float width; */ +/* float length; */ +/* float volume; */ +/* }; */ +/* */ +/* a. Write a function that passes a box structure by value and that */ +/* displays the value of each member. */ +/* */ +/* b. Write a function that passes the address of a box structure */ +/* and that sets the volume member to the product of the other */ +/* three dimensions. */ +/* */ +/* c. Write a simple program that uses these two functions. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include + +struct box { std::string maker; + float h; float w; float l; float v; +}; + +box input(void); +void set_volume(box *); +void display(box); + +box input() +{ + box inbox; + std::cout << "Please specify the maker of your box: "; + std::cin >> inbox.maker; + std::cout << "Please enter H W L of your box: "; + std::cin >> inbox.h >> inbox.w >> inbox.l; + return inbox; +} + +void set_volume(box * p_box) +{ + p_box->v = p_box->h * p_box->w * p_box->l; +} + +void display(const box the_box) +{ + std::cout << "Maker: " << the_box.maker + << ", height: " << the_box.h + << ", width: " << the_box.w + << ", length: " << the_box.l + << ", volume: " << the_box.v << std::endl; +} + + +int main() +{ + box the_box = input(); + set_volume(&the_box); + display(the_box); + return 0; +} diff --git a/austinov.07.functions_cpp_programming_modules/04.lottery.cpp b/austinov.07.functions_cpp_programming_modules/04.lottery.cpp new file mode 100644 index 0000000..0ca148d --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/04.lottery.cpp @@ -0,0 +1,45 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Many state lotteries use a variation of the simple lottery */ +/* portrayed by Listing7.4. In these variations you choose several */ +/* numbers from one set and call them the field numbers. */ +/* For example, you might select five numbers from the field of 1–47 */ +/* You also pick a single number (called a meganumber or a powerball */ +/* from a second range, such as 1 – 27. To win the grand prize, you */ +/* have to guess all the picks correctly. The chance of winning is */ +/* the product of the probability of picking all the field numbers */ +/* times the probability of picking the meganumber. For instance, */ +/* the probability of winning the example described here is the */ +/* product of the probability of picking 5 out of 47 correctly times */ +/* the probability of picking 1 out of 27 correctly. Modify Listing */ +/* 7.4 to calculate the probability of winning this kind of lottery. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include + +const unsigned NUM47 = 47; +const unsigned NUM27 = 27; +const unsigned PCKS5 = 5; +const unsigned PICK1 = 1; + +long double prob(unsigned, unsigned); +long double prob(unsigned n, unsigned p) +{ + long double result = 1.0; + for (; p > 0; n--, p--) + result = result * p / n ; + return result; +} + +int main() +{ + std::cout << "The probability of winnig for " << PCKS5 + << " out of " << NUM47 << " plus " << PICK1 + << " out of " << NUM27 << " is " + << prob(NUM47, PCKS5) * prob(NUM27, PICK1) + << "." << std::endl; + return 0; +} + diff --git a/austinov.07.functions_cpp_programming_modules/05.factorial.cpp b/austinov.07.functions_cpp_programming_modules/05.factorial.cpp new file mode 100644 index 0000000..581c15e --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/05.factorial.cpp @@ -0,0 +1,30 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Define a recursive function that takes an integer argument */ +/* and returns the factorial of that argument. */ +/* */ +/* Recall that 3 factorial, written 3!, equals 3 * 2!, */ +/* and so on, with 0! defined as 1. */ +/* */ +/* In general, if n is greater than zero, n! = n * (n - 1)!. */ +/* */ +/* Test your function in a program that uses a loop to allow */ +/* the user to enter various values for which the program */ +/* reports the factorial. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +long double f(unsigned); +long double f(unsigned n) { return 0 == n ? 1 : f(n - 1) * n; } + +int main() +{ + unsigned n; + std::cout << "Calculate Factorial (q to quit).\nPlease enter the n: "; + while(std::cin >> n) std::cout << n << "! is " << f(n) << std::endl + << "Enter another n (q to exit): "; + return 0; +} + diff --git a/austinov.07.functions_cpp_programming_modules/06.reverse.cpp b/austinov.07.functions_cpp_programming_modules/06.reverse.cpp new file mode 100644 index 0000000..e5c7722 --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/06.reverse.cpp @@ -0,0 +1,69 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that uses the following functions: */ +/* */ +/* fill_array() takes as arguments the name of an array of double */ +/* values and an array size. It prompts the user to enter double */ +/* values to be entered in the array. It ceases taking input when */ +/* the array is full or when the user enters non-numeric input, and */ +/* it returns the actual number of entries. */ +/* */ +/* show_array() takes as arguments the name of an array of double */ +/* values and an array size and displays the contents of the array. */ +/* */ +/* reverse_array() takes as arguments the name of an array of double */ +/* values and an array size and reverses the order of the values */ +/* stored in the array. */ +/* */ +/* The program should use these functions to fill an array, show the */ +/* array, reverse the array, show the array, reverse all but the */ +/* first and last elements of the array, and then show the array. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +unsigned fill_array(double [], unsigned); +void show_array(const double [], unsigned); +void reverse_array(double [], unsigned); + +const unsigned MAX_SZ = 20; + +unsigned fill_array(double ar[], unsigned sz) +{ + unsigned i = 0; + std::cout << "Please enter up to " << sz << " array members: "; + while (std::cin >> ar[i] && i < sz) i++; + return i < sz ? i : sz; +} + +void show_array(const double ar[], unsigned sz) +{ + for (unsigned i = 0; i < sz; i++) std::cout << " " << ar[i]; +} + +void reverse_array(double ar[], unsigned sz) +{ + double tmp = 0.0; + for (unsigned i = 0; i < sz / 2 + sz % 2; i++) { + tmp = ar[i]; + ar[i] = ar[sz - i - 1]; + ar[sz - i - 1] = tmp; + }; +} + +int main() +{ + double arr_of_dbl[MAX_SZ]; + unsigned size = fill_array(arr_of_dbl, MAX_SZ); + + show_array(arr_of_dbl, size); + std::cout << std::endl; + + reverse_array(arr_of_dbl, size); + show_array(arr_of_dbl, size); + + std::cout << std::endl; + return 0; +} + diff --git a/austinov.07.functions_cpp_programming_modules/07.range.cpp b/austinov.07.functions_cpp_programming_modules/07.range.cpp new file mode 100644 index 0000000..90d2e06 --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/07.range.cpp @@ -0,0 +1,83 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Redo Listing 7.7, modifying the three array-handling functions to */ +/* each use two pointer parameters to represent a range. */ +/* */ +/* The fill_array() function, instead of returning the actual number */ +/* of items read, should return a pointer to the location after the */ +/* last location filled; the other functions can use this pointer as */ +/* the second argument to identify the end of the data. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +const unsigned Max = 5; +double * fill_array(double [], unsigned); +void show_array(const double [], const double *); +void revalue(double, double [], const double *); + +double * fill_array(double ar[], unsigned limit) +{ + unsigned i; + double * pt = ar; + double temp; + for (i = 0; i < limit; i++) + { + std::cout << "Enter value #" << (i + 1) << ": "; + std::cin >> temp; + if (!std::cin) // bad input + { + std::cin.clear(); + while (std::cin.get() != '\n') + continue; + std::cout << "Bad input; input process terminated.\n"; + break; + } else + if (temp < 0) + break; + ar[i] = temp; + }; + return pt + i; +} + +void show_array(const double ar[], const double * pt) +{ + for (unsigned i = 0; ar + i < pt; i++) + { + std::cout << "Property #" << (i + 1) << ": $" << ar[i] << std::endl; + }; +} + +void revalue(double r, double ar[], const double * pt) +{ + for (int i = 0; ar + i < pt; i++) ar[i] *= r; +} + +int main() +{ + double properties[Max]; + + double * end_pt = fill_array(properties, Max); + show_array(properties, end_pt); + + if (end_pt > properties) + { + std::cout << "Enter revaluation factor: "; + double factor; + while (!(std::cin >> factor)) // bad input + { + std::cin.clear(); + while (std::cin.get() != '\n') + continue; + std::cout << "Bad input; Please enter a number: "; + }; + revalue(factor, properties, end_pt); + show_array(properties, end_pt); + }; + std::cout << "Done.\n"; + std::cin.get(); + std::cin.get(); + + return 0; +} diff --git a/austinov.07.functions_cpp_programming_modules/08.a.cpp b/austinov.07.functions_cpp_programming_modules/08.a.cpp new file mode 100644 index 0000000..e3bc3c9 --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/08.a.cpp @@ -0,0 +1,55 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Redo Listing 7.15 without using the arrayclass. Do two versions: */ +/* */ +/* a. Use an ordinary array of const char * for the strings */ +/* representing the season names, and use an ordinary array of */ +/* double for the expenses. */ +/* */ +/* b. Use an ordinary array of const char * for the strings */ +/* representing the season names, and use a structure whose sole */ +/* member is an ordinary array of double for the expenses. */ +/* (This design is similar to the basic design of the array class.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +const int SS = 4; +static const char* Snames[] = {"Spring", "Summer", "Fall", "Winter"}; + + +void fill(double (* )[SS]); +void show(double []); + +void fill(double (* p_to_a_of_d)[SS]) +{ + for (unsigned i = 0; i < SS; i++) + { + std::cout << "Enter " << Snames[i] << " expenses: "; + std::cin >> (*p_to_a_of_d)[i]; + }; +} + +void show(double da[]) +{ + double total = 0.0; + std::cout << "\nEXPENSES\n"; + for (int i = 0; i < SS; i++) + { + std::cout << Snames[i] << ": $" << da[i] << std::endl; + total += da[i]; + }; + std::cout << "Total Expenses: $" << total << std::endl; +} + +int main() +{ + double expenses[SS]; + + fill(&expenses); + show(expenses); + + return 0; +} + diff --git a/austinov.07.functions_cpp_programming_modules/08.b.cpp b/austinov.07.functions_cpp_programming_modules/08.b.cpp new file mode 100644 index 0000000..3bb4f56 --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/08.b.cpp @@ -0,0 +1,56 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Redo Listing 7.15 without using the arrayclass. Do two versions: */ +/* */ +/* a. Use an ordinary array of const char * for the strings */ +/* representing the season names, and use an ordinary array of */ +/* double for the expenses. */ +/* */ +/* b. Use an ordinary array of const char * for the strings */ +/* representing the season names, and use a structure whose sole */ +/* member is an ordinary array of double for the expenses. */ +/* (This design is similar to the basic design of the array class.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +const int SS = 4; +const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; + +struct exp_struct { double data[SS]; }; + +void fill(exp_struct *); +void show(exp_struct); + +void fill(exp_struct * p_exps) +{ + for (unsigned i = 0; i < SS; i++) + { + std::cout << "Enter " << Snames[i] << " expenses: "; + std::cin >> p_exps->data[i]; + }; +} + +void show(exp_struct exps) +{ + double total = 0.0; + std::cout << "\nEXPENSES\n"; + for (int i = 0; i < SS; i++) + { + std::cout << Snames[i] << ": $" << exps.data[i] << std::endl; + total += exps.data[i]; + }; + std::cout << "Total Expenses: $" << total << std::endl; +} + +int main() +{ + exp_struct expenses; + + fill(&expenses); + show(expenses); + + return 0; +} + diff --git a/austinov.07.functions_cpp_programming_modules/09.astruct.cpp b/austinov.07.functions_cpp_programming_modules/09.astruct.cpp new file mode 100644 index 0000000..3f3e9e6 --- /dev/null +++ b/austinov.07.functions_cpp_programming_modules/09.astruct.cpp @@ -0,0 +1,97 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* This exercise provides practice in writing functions dealing with */ +/* arrays and structures. The following is a program skeleton. */ +/* Complete it by providing the described functions: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include + +const int SLEN = 30; + +struct student +{ + char fullname[SLEN]; + char hobby[SLEN]; + int ooplevel; +}; + +// getinfo() has two arguments: a pointer to the first element of +// an array of student structures and an int representing the +// number of elements of the array. The function solicits and +// stores data about students. It terminates input upon filling +// the array or upon encountering a blank line for the student +// name. The function returns the actual number of array elements +// filled. +unsigned getinfo(student [], unsigned); + +// display1() takes a student structure as an argument +// and displays its contents +void display1(student); + +// display2() takes the addressof student structure as an +// argument and displays the structure’s contents +void display2(const student *); + +// display3() takes the address of the first element of an array +// of student structures and the number of array elements as +// arguments and displays the contents of the structures +void display3(const student [], unsigned); + + +unsigned getinfo(student pa[], unsigned n) +{ + unsigned i = 0; + do { + std::cout << "Please enter the name: "; + if (!std::cin.getline(pa[i].fullname, SLEN)) + break; + std::cout << "Please enter the hobby: "; + std::cin.getline(pa[i].hobby, SLEN); + std::cout << "Specify the ooplevel: "; + std::cin >> pa[i].ooplevel; + while (std::cin.get() != '\n') continue; + i++; + } while (i < n); + return i; +} + +void display1(student st) +{ + std::cout << st.fullname << " " + << st.hobby << " " + << st.ooplevel << std::endl; +} + +void display2(const student * ps) +{ + std::cout << ps->fullname << " " + << ps->hobby << " " + << ps->ooplevel << std::endl; +} + +void display3(const student pa[], unsigned n) +{ + for (unsigned i = 0; i < n; i++) display1(pa[i]); +} + +int main() +{ + std::cout << "Enter class size: "; + unsigned class_size; + std::cin >> class_size; + while (std::cin.get() != '\n') continue; + student * ptr_stu = new student[class_size]; + unsigned entered = getinfo(ptr_stu, class_size); + for (unsigned i = 0; i < entered; i++) + { + display1(ptr_stu[i]); + display2(&ptr_stu[i]); + }; + display3(ptr_stu, entered); + delete [] ptr_stu; + std::cout << "Done\n"; + return 0; +} + diff --git a/austinov.08.adventures_in_functions/01.printn.cpp b/austinov.08.adventures_in_functions/01.printn.cpp new file mode 100644 index 0000000..5fbf99b --- /dev/null +++ b/austinov.08.adventures_in_functions/01.printn.cpp @@ -0,0 +1,51 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a function that normally takes one argument, the address of */ +/* a string, and prints that string once. However, if a second, type */ +/* int, argument is provided and is non zero, the function should */ +/* print the string a number of times equal to the number of times */ +/* that function has been called at that point. (Note that the */ +/* number of times the string is printed is not equal to the value */ +/* of the second argument; it is equal to the number of times the */ +/* function has been called). Yes, this is a silly function, but it */ +/* makes you use some of the techniques discussed in this chapter. */ +/* Use the function in a simple program that demonstrates how the */ +/* function works. */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include + + +void printn(std::string content, int flag = 0); +void printn(std::string content, int flag) +{ + static int run_count = 0; + if (0 == flag) { + std::cout << content << std::endl; + } else + for (int i = 0; i < run_count; i++) + std::cout << content << std::endl; + run_count++; +} + +int main() +{ + std::string testr = "This is a test string."; + + std::cout << "1st run: " << std::endl; + printn(testr); + std::cout << "2d run: " << std::endl; + printn(testr); + std::cout << "3d run: " << std::endl; + printn(testr); + for (int i = 4; i < 10; i++) + { + std::cout << i << "th run (with second arg set to" + << i << "): " << std::endl; + printn(testr, i); + }; + std::cout << "Last run (with single arg again): " << std::endl; + printn(testr); + return 0; +} diff --git a/austinov.08.adventures_in_functions/02.cdbar.cpp b/austinov.08.adventures_in_functions/02.cdbar.cpp new file mode 100644 index 0000000..0b4b3be --- /dev/null +++ b/austinov.08.adventures_in_functions/02.cdbar.cpp @@ -0,0 +1,57 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* The CandyBar structure contains three members. The first member */ +/* holds the brand name of a candy bar. The second member holds the */ +/* weight (which may have a fractional part) of the candy bar, and */ +/* the third member holds the number of calories (an integer value) */ +/* in the candy bar. */ +/* */ +/* Write a program that uses a function that takes as arguments a */ +/* reference to CandyBar, a pointer-to-char, a double and an int */ +/* and uses the last three values to set the corresponding members */ +/* of the structure. The last three arguments should have default */ +/* values of “Millennium Munch”, 2.85, and 350. */ +/* */ +/* Also the program should use a function that takes a reference to */ +/* a CandyBar as an argument and displays the contents of the */ +/* structure. Use const where appropriate. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include + +struct CandyBar +{ + std::string name; + double weight; + unsigned kcal; +}; + +void display(const CandyBar &); +void fill(CandyBar & cb, const char * name = "Millenium Munch", + double weight = 2.85, unsigned kcal = 350); + +void fill(CandyBar & cb, const char * name, double weight, unsigned kcal) +{ + cb.name = name; + cb.weight = weight; + cb.kcal = kcal; +} + +void display(const CandyBar & cb) +{ + std::cout << "Brand name: " << cb.name + << ", Weight: " << cb.weight + << ", Calories: " << cb.kcal << std::endl; +} + +int main() +{ + CandyBar cb; + fill(cb); + display(cb); + fill(cb, "Olenka", 0.950, 222); + display(cb); + return 0; +} diff --git a/austinov.08.adventures_in_functions/03.upper.cpp b/austinov.08.adventures_in_functions/03.upper.cpp new file mode 100644 index 0000000..66b0006 --- /dev/null +++ b/austinov.08.adventures_in_functions/03.upper.cpp @@ -0,0 +1,49 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a function that takes a reference to a string object as its */ +/* parameter and that converts the contents of the string to upper */ +/* case. Use the toupper() function described in Table 6.4 of */ +/* Chapter 6. Write a program that uses a loop which allows you to */ +/* test the function with different input. */ +/* A sample run might look like this: */ +/* */ +/* Enter a string (q to quit): go away */ +/* GO AWAY */ +/* Next string (q to quit): good grief! */ +/* GOOD GRIEF! */ +/* Next string (q to quit): q */ +/* Bye. */ +/* */ +/* The following is a program skeleton: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +# include +# include +# include + +const std::string & to_upper(std::string & inputstr_ref); +const std::string & to_upper(std::string & inputstr_ref) +{ + for (unsigned i = 0; i < inputstr_ref.size(); i++) + { + if (std::islower(inputstr_ref.at(i))) + inputstr_ref.at(i) = std::toupper(inputstr_ref.at(i)); + }; + return inputstr_ref; +} + +int main() +{ + std::string input_str; + std::cout << "Enter a string (q to quit): "; + while (std::getline(std::cin, input_str) && "q" != input_str) + { + std::cout << to_upper(input_str) << std::endl; + std::cout << "Next string (q to quit): "; + }; + std::cout << "Bye." << std::endl; + + return 0; +} + diff --git a/austinov.08.adventures_in_functions/04.skel.cpp b/austinov.08.adventures_in_functions/04.skel.cpp new file mode 100644 index 0000000..81d1b6c --- /dev/null +++ b/austinov.08.adventures_in_functions/04.skel.cpp @@ -0,0 +1,94 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* The following is a program skeleton: */ +/* */ +/* #include */ +/* using namespace std; */ +/* #include // for strlen(), strcpy() */ +/* struct stringy { */ +/* char * str; // points to a string */ +/* int ct; // length of string (not counting '\0') */ +/* }; */ +/* // prototypes for set(), show(), and show() go here */ +/* int main() */ +/* { */ +/* stringy beany; */ +/* char testing[] = "Reality isn't what it used to be."; */ +/* set(beany, testing); // first argument is a reference, */ +/* // allocates space to hold copy of testing, */ +/* // sets str member of beany to point to the */ +/* // new block, copies testing to new block, */ +/* // and sets ct member of beany */ +/* show(beany); // prints member string once */ +/* show(beany, 2); //prints member string twice */ +/* testing[0] = 'D'; */ +/* testing[1] = 'u'; */ +/* show(testing); // prints testing string once */ +/* show(testing, 3); // prints testing string thrice */ +/* show("Done!"); */ +/* return 0; */ +/* } */ +/* */ +/* Complete this skeleton by providing the described functions and */ +/* prototypes. Note that there should be two show() functions, each */ +/* using default arguments. Use const arguments when appropriate. */ +/* Note that set() should use new to allocate sufficient space to */ +/* hold the designated string. The techniques used here are similar */ +/* to those used in designing and implementing classes. (You might */ +/* have to alter the header filenames and delete the using directive */ +/* depending on your compiler.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include // for strlen(), strcpy() + +struct stringy { + char * str; // points to a string + int ct; // length of string (not counting '\0') +}; + +// prototypes for set(), show(), and show() go here +void set(stringy &, const char *); +void show(const stringy &, unsigned n = 1); +void show(const char *, unsigned n = 1); + +void set(stringy & stringy_ref, const char * content) +{ + stringy_ref.ct = strlen(content); + stringy_ref.str = new char[stringy_ref.ct + 1]; + strcpy(stringy_ref.str, content); +} + +void show(const stringy & stringy_ref, unsigned n) +{ + for (unsigned i = 0; i < n; i++) std::cout << stringy_ref.str << std::endl; +} + +void show(const char * p2ch, unsigned n) +{ + for (unsigned i = 0; i < n; i++) std::cout << p2ch << std::endl; +} + +int main() +{ + stringy beany; + char testing[] = "Reality isn't what it used to be."; + set(beany, testing); /* + // first argument is a reference, + // allocates space to hold copy of testing, + // sets str member of beany to point to the + // new block, copies testing to new block, + // and sets ct member of beany + */ + show(beany); // prints member string once + show(beany, 2); //prints member string twice + testing[0] = 'D'; + testing[1] = 'u'; + show(testing); // prints testing string once + show(testing, 3); // prints testing string thrice + show("Done!"); + delete beany.str; + return 0; +} + diff --git a/austinov.08.adventures_in_functions/05.max5.cpp b/austinov.08.adventures_in_functions/05.max5.cpp new file mode 100644 index 0000000..f043012 --- /dev/null +++ b/austinov.08.adventures_in_functions/05.max5.cpp @@ -0,0 +1,32 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a template function max5() that takes as its argument an */ +/* array of five items of type T and returns the largest item in the */ +/* array. (Because the size is fixed it can be hard-coded into the */ +/* loop instead of being passed as an argument.) Test it in a */ +/* program that uses the function with an array of five int value */ +/* and an array of five double values. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +const size_t MAX = 5; + +template +T max5(T arr[MAX]) +{ + T max = 0; + for (unsigned i = 0; i < MAX; i++) max = arr[i] > max ? arr[i] : max; + return max; +} + +int main() +{ + int ints[MAX] = {1, 2, 3, 4, 5}; + double doubles[MAX] = {1.1, 2.2, 3.3, 4.4, 5.5}; + std::cout << max5(ints) << std::endl; + std::cout << max5(doubles) << std::endl; + return 0; +} + diff --git a/austinov.08.adventures_in_functions/05.maxn.cpp b/austinov.08.adventures_in_functions/05.maxn.cpp new file mode 100644 index 0000000..03059ed --- /dev/null +++ b/austinov.08.adventures_in_functions/05.maxn.cpp @@ -0,0 +1,46 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a template function maxn() that takes as its arguments an */ +/* array of items of type T and an integer representing the number */ +/* of elements in the array and that returns the largest item in the */ +/* array. Test it in a program that uses the function template with */ +/* an array of six int value and an array of four double values. The */ +/* program should also include a specialization that takes an array */ +/* of pointers-to-char as an argument and the number of pointers as */ +/* a second argument and that returns the address of the longest */ +/* string. If multiple strings are tied for having the longest */ +/* length, the function should return the address of the first one */ +/* tied for longest. Test the specialization with an array of five */ +/* string pointers. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +template +T max_n(T arr[], unsigned n) +{ + T max = 0; + for (unsigned i = 0; i < n; i++) max = arr[i] > max ? arr[i] : max; + return max; +} + +template <> char * max_n(char * arr[], unsigned n) +{ + char * pmax = arr[0]; + for (unsigned i = 0; i < n; i++) + pmax = strlen(arr[i]) > strlen(pmax) ? arr[i] : pmax; + return pmax; +} + +int main() +{ + int ints[] = {1, 2, 3, 4, 5, 6}; + double doubles[] = {1.1, 2.2, 3.3, 4.4}; + char * chars[] = {"One", "Two", "Three", "Four", "Five"}; + std::cout << max_n(ints, 6) << std::endl; + std::cout << max_n(doubles, 4) << std::endl; + std::cout << max_n(chars, 5) << std::endl; + return 0; +} + diff --git a/austinov.08.adventures_in_functions/06.sumarr.cpp b/austinov.08.adventures_in_functions/06.sumarr.cpp new file mode 100644 index 0000000..f846a36 --- /dev/null +++ b/austinov.08.adventures_in_functions/06.sumarr.cpp @@ -0,0 +1,59 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Modify Listing 8.14 so that it uses two template functions called */ +/* SumArray() to return the sum of the array contents instead of */ +/* displaying the contents.The pro-gram now should report the total */ +/* number of things and the sum of all the debts. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +template void SumArray(T arr[], int n); +template void SumArray(T * arr[], int n); + +struct debts {char name[50]; double amount;}; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +template void SumArray(T arr[], int n) +{ + T sum = 0; + std::cout << "template A\nSum: "; + for (int i = 0; i < n; i++) sum += arr[i]; + std::cout << sum << std::endl; +} + +template void SumArray(T * arr[], int n) +{ + T sum = 0; + std::cout << "template B\nSum: "; + for (int i = 0; i < n; i++) sum += *arr[i]; + std::cout << sum << std::endl; +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +int main() +{ + int things[6] = {13, 31, 103, 301, 310, 130}; + + struct debts mr_E[3] = + { + {"Ima Wolfe", 2400.0}, + {"Ura Foxe", 1300.0}, + {"Iby Stout", 1800.0} + }; + + double * pd[3]; + for (int i = 0; i < 3; i++) pd[i] = &mr_E[i].amount; + + std::cout << "Listing Mr. E's total number of things:\n"; + SumArray(things, 6); // uses template A + + std::cout << "Listing Mr. E's debts sum:\n"; + SumArray(pd, 3); // uses template B (more specialized) + + return 0; +} + From ca4e72b9a993cf93be74429cd8b700eee8827a8f Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 25 Jun 2013 18:32:18 +0300 Subject: [PATCH 11/15] Chapter 9 Assignments --- .../01.golf.h | 54 +++++++++++ .../01.golf0.cpp | 91 +++++++++++++++++++ .../01.golf1.cpp | 84 +++++++++++++++++ .../02.redo99.cpp | 36 ++++++++ .../03.chaff.cpp | 44 +++++++++ .../04.main.cpp | 29 ++++++ .../04.sales.cpp | 64 +++++++++++++ .../04.sales.h | 49 ++++++++++ 8 files changed, 451 insertions(+) create mode 100644 austinov.09.memory_models_and_namespaces/01.golf.h create mode 100644 austinov.09.memory_models_and_namespaces/01.golf0.cpp create mode 100644 austinov.09.memory_models_and_namespaces/01.golf1.cpp create mode 100644 austinov.09.memory_models_and_namespaces/02.redo99.cpp create mode 100644 austinov.09.memory_models_and_namespaces/03.chaff.cpp create mode 100644 austinov.09.memory_models_and_namespaces/04.main.cpp create mode 100644 austinov.09.memory_models_and_namespaces/04.sales.cpp create mode 100644 austinov.09.memory_models_and_namespaces/04.sales.h diff --git a/austinov.09.memory_models_and_namespaces/01.golf.h b/austinov.09.memory_models_and_namespaces/01.golf.h new file mode 100644 index 0000000..1ad8ec5 --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/01.golf.h @@ -0,0 +1,54 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a header file: */ +/* */ +/* Notethat setgolf() is overloaded. Using the first version of */ +/* setgolf() would look like this: */ +/* */ +/* golf ann; */ +/* setgolf(ann, "Ann Birdfree", 24); */ +/* */ +/* The function call provides the information that’s stored in the */ +/* ann structure. Using the second version of setgolf() would look */ +/* like this: */ +/* */ +/* golf andy; */ +/* setgolf(andy); */ +/* */ +/* The function would prompt the user to enter the name and handicap */ +/* and store them in the andy structure. This function could (but */ +/* doesn’t need to) use the first version internally. */ +/* */ +/* Put together a multifile program based on this header. One file, */ +/* named golf.cpp, should provide suitable function definitions to */ +/* match the prototypes in the header file. A second file should */ +/* contain main() and demonstrate all the features of the prototyped */ +/* functions. For example, a loop should solicit input for an array */ +/* of golf structures and terminate when the array is full or the */ +/* user enters an empty string for the golfer’s name. The main() */ +/* function should use only the prototyped functions to access the */ +/* golf structures. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// golf.h -- for pe9-1.cpp + +const int Len = 40; +struct golf { char fullname[Len]; int handicap; }; + +// non-interactive version: +// function sets golf structure to provided name, handicap +// using values passed as arguments to the function +void setgolf(golf & g, const char * name, int hc); + +// interactive version: +// function solicits name and handicap from user +// and sets the members of g to the values entered +// returns 1 if name is entered, 0 if name is empty string +int setgolf(golf & g); + +// function resets handicap to new value +void handicap(golf & g, int hc); + +// function displays contents of golf structure +void showgolf(const golf & g); diff --git a/austinov.09.memory_models_and_namespaces/01.golf0.cpp b/austinov.09.memory_models_and_namespaces/01.golf0.cpp new file mode 100644 index 0000000..35b6ce3 --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/01.golf0.cpp @@ -0,0 +1,91 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a header file: */ +/* */ +/* // golf.h -- for pe9-1.cpp */ +/* const int Len = 40; */ +/* struct golf */ +/* { */ +/* char fullname[Len]; */ +/* int handicap; */ +/* }; */ +/* // non-interactive version: */ +/* // function sets golf structure to provided name, handicap */ +/* // using values passed as arguments to the function */ +/* void setgolf(golf & g, const char * name, int hc); */ +/* // interactive version: */ +/* // function solicits name and handicap from user */ +/* // and sets the members of g to the values entered */ +/* // returns 1 if name is entered, 0 if name is empty string */ +/* int setgolf(golf & g); */ +/* // function resets handicap to new value */ +/* void handicap(golf & g, int hc); */ +/* // function displays contents of golf structure */ +/* void showgolf(const golf & g); */ +/* */ +/* Notethat setgolf() is overloaded. Using the first version of */ +/* setgolf() would look like this: */ +/* */ +/* golf ann; */ +/* setgolf(ann, "Ann Birdfree", 24); */ +/* */ +/* The function call provides the information that’s stored in the */ +/* ann structure. Using the second version of setgolf() would look */ +/* like this: */ +/* */ +/* golf andy; */ +/* setgolf(andy); */ +/* */ +/* The function would prompt the user to enter the name and handicap */ +/* and store them in the andy structure. This function could (but */ +/* doesn’t need to) use the first version internally. */ +/* */ +/* Put together a multifile program based on this header. One file, */ +/* named golf.cpp, should provide suitable function definitions to */ +/* match the prototypes in the header file. A second file should */ +/* contain main() and demonstrate all the features of the prototyped */ +/* functions. For example, a loop should solicit input for an array */ +/* of golf structures and terminate when the array is full or the */ +/* user enters an empty string for the golfer’s name. The main() */ +/* function should use only the prototyped functions to access the */ +/* golf structures. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include +#include "01.golf.h" + +void setgolf(golf & g, const char * name, int hc) +{ + std::strcpy(g.fullname, name); + g.handicap = hc; +} + +int setgolf(golf & g) +{ + int result = 0; + char name[Len]; + int handicap = 0; + std::cout << "Please enter the name: "; + std::cin.ignore(Len, '\n'); + if (std::cin.getline(name, Len) && '\0' != name[0]) + { + std::cout << "Please enter the handicap: "; + std::cin >> handicap; + setgolf(g, name, handicap); + result = 1; + }; + return result; +} + +void handicap(golf & g, int hc) +{ + g.handicap = hc; +} + + +void showgolf(const golf & g) +{ + std::cout << g.fullname << ", " << g.handicap << std::endl; +} diff --git a/austinov.09.memory_models_and_namespaces/01.golf1.cpp b/austinov.09.memory_models_and_namespaces/01.golf1.cpp new file mode 100644 index 0000000..6b85239 --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/01.golf1.cpp @@ -0,0 +1,84 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a header file: */ +/* */ +/* // golf.h -- for pe9-1.cpp */ +/* const int Len = 40; */ +/* struct golf */ +/* { */ +/* char fullname[Len]; */ +/* int handicap; */ +/* }; */ +/* // non-interactive version: */ +/* // function sets golf structure to provided name, handicap */ +/* // using values passed as arguments to the function */ +/* void setgolf(golf & g, const char * name, int hc); */ +/* // interactive version: */ +/* // function solicits name and handicap from user */ +/* // and sets the members of g to the values entered */ +/* // returns 1 if name is entered, 0 if name is empty string */ +/* int setgolf(golf & g); */ +/* // function resets handicap to new value */ +/* void handicap(golf & g, int hc); */ +/* // function displays contents of golf structure */ +/* void showgolf(const golf & g); */ +/* */ +/* Notethat setgolf() is overloaded. Using the first version of */ +/* setgolf() would look like this: */ +/* */ +/* golf ann; */ +/* setgolf(ann, "Ann Birdfree", 24); */ +/* */ +/* The function call provides the information that’s stored in the */ +/* ann structure. Using the second version of setgolf() would look */ +/* like this: */ +/* */ +/* golf andy; */ +/* setgolf(andy); */ +/* */ +/* The function would prompt the user to enter the name and handicap */ +/* and store them in the andy structure. This function could (but */ +/* doesn’t need to) use the first version internally. */ +/* */ +/* Put together a multifile program based on this header. One file, */ +/* named golf.cpp, should provide suitable function definitions to */ +/* match the prototypes in the header file. A second file should */ +/* contain main() and demonstrate all the features of the prototyped */ +/* functions. For example, a loop should solicit input for an array */ +/* of golf structures and terminate when the array is full or the */ +/* user enters an empty string for the golfer’s name. The main() */ +/* function should use only the prototyped functions to access the */ +/* golf structures. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include "01.golf.h" + +int main() +{ + size_t ar_sz = 0; + std::cout << "Please enter the number of golfers: " << std::flush; + while (!(std::cin >> ar_sz)) { + while (std::cin.get() != '\n') continue; + std::cout << "Please enter the integer value: " << std::flush; + std::cin.clear(); + }; + std::cout << "You've entered " << ar_sz << std::endl; + + golf * golfers = new golf[ar_sz]; + + unsigned i = 0; + while (i < ar_sz && setgolf(golfers[i])) i++; + + std::cout << std::endl << "Here are your golfers: " << std::endl; + + for (unsigned g = 0; g < i; g++) showgolf(golfers[g]); + + + + + + return 0; +} + diff --git a/austinov.09.memory_models_and_namespaces/02.redo99.cpp b/austinov.09.memory_models_and_namespaces/02.redo99.cpp new file mode 100644 index 0000000..af252bb --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/02.redo99.cpp @@ -0,0 +1,36 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Redo Listing 9.9, replacing the character array with a string */ +/* object. The program should no longer have to check whether the */ +/* input string fits, and it can compare the input string to "" to */ +/* check for an empty line. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include + +void strcount(const std::string); + +void strcount(const std::string str) +{ + static int total = 0; + size_t count = str.size(); + std::cout << "\"" << str << "\" contains " << count << " characters\n"; + std::cout << (total += count) << " characters total\n"; +} + +int main() +{ + std::string input; + std::cout << "Enter a line:\n"; + while (std::getline(std::cin, input) && "" != input) + { + strcount(input); + std::cout << "Enter next line (empty line to quit):\n"; + std::getline(std::cin, input); + } + std::cout << "Bye\n"; + return 0; +} + diff --git a/austinov.09.memory_models_and_namespaces/03.chaff.cpp b/austinov.09.memory_models_and_namespaces/03.chaff.cpp new file mode 100644 index 0000000..fc6b732 --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/03.chaff.cpp @@ -0,0 +1,44 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a program that uses placement new to place an array of two */ +/* such structures in a buffer. Then assign values to the structure */ +/* members (remembering to use strcpy() for the char array) and use */ +/* a loop to display the contents. Option 1 is to use a static array */ +/* like that in Listing 9.10, for the buffer. Option 2 is to use the */ +/* regular new to allocate the buffer. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +struct chaff +{ + char dross[20]; + int slag; +}; + +char buffer[50]; + +int main() +{ + + chaff * p_bufchaf2 = new (buffer) chaff[2]; + + strcpy(p_bufchaf2[0].dross, "Chaff 0 dross 0"); + strcpy(p_bufchaf2[1].dross, "Chaff 1 dross 0"); + + p_bufchaf2[0].slag = 42; + p_bufchaf2[1].slag = 43; + + for (unsigned i = 0; i < 2; i++) + { + std::cout << p_bufchaf2[i].dross << ' ' + << p_bufchaf2[i].slag << std::endl; + }; + + std::cout << "&buffer = " << &buffer << std::endl; + std::cout << "p_bufchaf2 = " << p_bufchaf2 << std::endl; + + return 0; +} + diff --git a/austinov.09.memory_models_and_namespaces/04.main.cpp b/austinov.09.memory_models_and_namespaces/04.main.cpp new file mode 100644 index 0000000..41bc7e3 --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/04.main.cpp @@ -0,0 +1,29 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a three-file program based on the namespace from sales.h: */ +/* */ +/* The first file should be a header file that contains the */ +/* namespace. The second file should be a source code file that */ +/* extends the namespace to provide definitions for the three */ +/* prototyped functions. The third file should declare two Sales */ +/* objects. It should use the interactive version of setSales() */ +/* to provide values for one structure and the non-interactive */ +/* version of setSales() to provide values for the second */ +/* structure. It should display the contents of both structures */ +/* by using showSales(). */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "04.sales.h" + +int main() +{ + + SALES::Sales sls0; + + SALES::setSales(sls0); + + SALES::showSales(sls0); + + return 0; +} diff --git a/austinov.09.memory_models_and_namespaces/04.sales.cpp b/austinov.09.memory_models_and_namespaces/04.sales.cpp new file mode 100644 index 0000000..696b4a5 --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/04.sales.cpp @@ -0,0 +1,64 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a three-file program based on the namespace from sales.h: */ +/* */ +/* The first file should be a header file that contains the */ +/* namespace. The second file should be a source code file that */ +/* extends the namespace to provide definitions for the three */ +/* prototyped functions. The third file should declare two Sales */ +/* objects. It should use the interactive version of setSales() */ +/* to provide values for one structure and the non-interactive */ +/* version of setSales() to provide values for the second */ +/* structure. It should display the contents of both structures */ +/* by using showSales(). */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "04.sales.h" + +namespace SALES +{ + void setSales(Sales & s, const double ar[], int n = QUARTERS) + { + double max = ar[0]; + double min = ar[0]; + double tot = 0; + for (int i = 0; i < n; i++) + { + if (ar[i] > max) max = ar[i]; + if (ar[i] < min) min = ar[i]; + tot += (s.sales[i] = ar[i]); + }; + if (n < QUARTERS) + for (int i = n; i < QUARTERS; i++) s.sales[i] = 0.0; + s.average = tot / n; + s.max = max; + s.min = min; + } + + void setSales(Sales & s) + { + int len = QUARTERS; + double arr[QUARTERS]; + for (int i = 0; i < QUARTERS; i++) + { + std::cout << "Sales for quarter " << 1 + i << ": "; + if (!(std::cin >> arr[i])) + { + len = i; + break; + }; + }; + setSales(s, arr, (QUARTERS == len) ? QUARTERS : len); + } + + void showSales(const Sales & s) + { + std::cout << "Quarterly Sales:" << std::flush; + for (unsigned i = 0; i < QUARTERS; i++) + std::cout << (0 == i ? " " : ", ") << s.sales[i] << std::flush; + std::cout << std::endl << "Average: " << s.average + << ", Max: " << s.max + << ", Min: " << s.min << std::endl; + } +} diff --git a/austinov.09.memory_models_and_namespaces/04.sales.h b/austinov.09.memory_models_and_namespaces/04.sales.h new file mode 100644 index 0000000..625b5ed --- /dev/null +++ b/austinov.09.memory_models_and_namespaces/04.sales.h @@ -0,0 +1,49 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Write a three-file program based on the following namespace: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include + +namespace SALES +{ + const int QUARTERS = 4; + struct Sales + { + double sales[QUARTERS]; + double average; + double max; + double min; + }; +// copies the lesser of 4 or n items from the array ar +// to the sales member of s and computes and stores the +// average, maximum, and minimum values of the entered items; +// remaining elements of sales, if any, set to 0 +void setSales(Sales & s, const double ar[], int n); + +// gathers sales for 4 quarters interactively, stores them +// in the sales member of s and computes and stores the +// average, maximum, and minimum values +void setSales(Sales & s); + +// display all information in structure s +void showSales(const Sales & s); + +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* The first file should be a header file that contains the */ +/* namespace. The second file should be a source code file that */ +/* extends the namespace to provide definitions for the three */ +/* prototyped functions. The third file should declare two Sales */ +/* objects. It should use the interactive version of setSales() */ +/* to provide values for one structure and the non-interactive */ +/* version of setSales() to provide values for the second */ +/* structure. It should display the contents of both structures */ +/* by using showSales(). */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + From d5345330a5a86123e7d15f6fc0f7092deca74907 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 25 Jun 2013 18:58:06 +0300 Subject: [PATCH 12/15] Added second case to task 04 --- austinov.09.memory_models_and_namespaces/04.main.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/austinov.09.memory_models_and_namespaces/04.main.cpp b/austinov.09.memory_models_and_namespaces/04.main.cpp index 41bc7e3..aed84a1 100644 --- a/austinov.09.memory_models_and_namespaces/04.main.cpp +++ b/austinov.09.memory_models_and_namespaces/04.main.cpp @@ -20,10 +20,15 @@ int main() { SALES::Sales sls0; + SALES::Sales sls1; SALES::setSales(sls0); + const double arr1[] = {12.34, 56.78, 91.0, 11.12}; + SALES::setSales(sls1, arr1, 4); + SALES::showSales(sls0); + SALES::showSales(sls1); return 0; } From 0c22c8cdb85bf5916f3df640e52e372eed31df80 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Mon, 1 Jul 2013 10:40:54 +0300 Subject: [PATCH 13/15] Chapter 10 Assignments --- austinov.10.objects_and_classes/01.q5.cpp | 9 +++ austinov.10.objects_and_classes/02.main.cpp | 48 ++++++++++++ austinov.10.objects_and_classes/02.person.cpp | 59 +++++++++++++++ austinov.10.objects_and_classes/02.person.h | 37 +++++++++ austinov.10.objects_and_classes/03.golf.cpp | 46 ++++++++++++ austinov.10.objects_and_classes/03.golf.h | 32 ++++++++ austinov.10.objects_and_classes/03.main.cpp | 43 +++++++++++ austinov.10.objects_and_classes/04.main.cpp | 25 +++++++ austinov.10.objects_and_classes/04.sales.cpp | 58 ++++++++++++++ austinov.10.objects_and_classes/04.sales.h | 31 ++++++++ austinov.10.objects_and_classes/05.main.cpp | 75 +++++++++++++++++++ austinov.10.objects_and_classes/05.stack.cpp | 46 ++++++++++++ austinov.10.objects_and_classes/05.stack.h | 50 +++++++++++++ austinov.10.objects_and_classes/06.main.cpp | 29 +++++++ austinov.10.objects_and_classes/06.move.cpp | 33 ++++++++ austinov.10.objects_and_classes/06.move.h | 29 +++++++ austinov.10.objects_and_classes/07.plorg.cpp | 66 ++++++++++++++++ austinov.10.objects_and_classes/; | 31 ++++++++ 18 files changed, 747 insertions(+) create mode 100644 austinov.10.objects_and_classes/01.q5.cpp create mode 100644 austinov.10.objects_and_classes/02.main.cpp create mode 100644 austinov.10.objects_and_classes/02.person.cpp create mode 100644 austinov.10.objects_and_classes/02.person.h create mode 100644 austinov.10.objects_and_classes/03.golf.cpp create mode 100644 austinov.10.objects_and_classes/03.golf.h create mode 100644 austinov.10.objects_and_classes/03.main.cpp create mode 100644 austinov.10.objects_and_classes/04.main.cpp create mode 100644 austinov.10.objects_and_classes/04.sales.cpp create mode 100644 austinov.10.objects_and_classes/04.sales.h create mode 100644 austinov.10.objects_and_classes/05.main.cpp create mode 100644 austinov.10.objects_and_classes/05.stack.cpp create mode 100644 austinov.10.objects_and_classes/05.stack.h create mode 100644 austinov.10.objects_and_classes/06.main.cpp create mode 100644 austinov.10.objects_and_classes/06.move.cpp create mode 100644 austinov.10.objects_and_classes/06.move.h create mode 100644 austinov.10.objects_and_classes/07.plorg.cpp create mode 100644 austinov.10.objects_and_classes/; diff --git a/austinov.10.objects_and_classes/01.q5.cpp b/austinov.10.objects_and_classes/01.q5.cpp new file mode 100644 index 0000000..9abf314 --- /dev/null +++ b/austinov.10.objects_and_classes/01.q5.cpp @@ -0,0 +1,9 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Provide method definitions for the class described in Question 5 */ +/* and write a short program that illustrates all the features. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// can't figure out what the question 5 is + diff --git a/austinov.10.objects_and_classes/02.main.cpp b/austinov.10.objects_and_classes/02.main.cpp new file mode 100644 index 0000000..457f0d1 --- /dev/null +++ b/austinov.10.objects_and_classes/02.main.cpp @@ -0,0 +1,48 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a rather simple class definition: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "02.person.h" /* the actual definition is in a header file */ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* It uses both a string object and a character array so that you */ +/* can compare how the two forms are used. */ +/* Write a program that completes the implementation by providing */ +/* code for the undefined methods. The program in which you use the */ +/* class should also use the three possible constructor calls (no */ +/* arguments, one argument, and two arguments) and the two display */ +/* methods. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +int main() +{ + using std::cout; + using std::endl; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here’s an example that uses the constructors and methods: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + + Person one; // use default constructor + Person two("Smythecraft"); // use #2 with one default argument + Person three("Dimwiddy", "Sam"); // use #2, no defaults + one.Show(); + cout << endl; + one.FormalShow(); + // etc. for two and three + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + + two.Show(); + two.FormalShow(); + three.Show(); + three.FormalShow(); + +} + diff --git a/austinov.10.objects_and_classes/02.person.cpp b/austinov.10.objects_and_classes/02.person.cpp new file mode 100644 index 0000000..bdf023f --- /dev/null +++ b/austinov.10.objects_and_classes/02.person.cpp @@ -0,0 +1,59 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a rather simple class definition: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "02.person.h" /* the definition is found in 02.person.h */ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* It uses both a string object and a character array so that you */ +/* can compare how the two forms are used. */ +/* Write a program that completes the implementation by providing */ +/* code for the undefined methods. The program in which you use the */ +/* class should also use the three possible constructor calls (no */ +/* arguments, one argument, and two arguments) and the two display */ +/* methods. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +Person::Person(const string & ln, const char * fn) +{ + lname = ln; + if (strlen(fn) > LIMIT) + { + std::cerr << "First name length is more than " << LIMIT + << ". The redundant characters will be discarded"; + }; + std::strcpy(fname, fn); +} + +void Person::Show(void) const +{ + std::cout << fname << ' ' << lname << std::endl; +} + +void Person::FormalShow(void) const +{ + std::cout << lname << ", " << fname << std::endl; +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here’s an example that uses the constructors and methods: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/* + Person one; // use default constructor + Person two("Smythecraft"); // use #2 with one default argument + Person three("Dimwiddy", "Sam"); // use #2, no defaults + one.Show(); + cout << endl; + one.FormalShow(); + // etc. for two and three +*/ + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + diff --git a/austinov.10.objects_and_classes/02.person.h b/austinov.10.objects_and_classes/02.person.h new file mode 100644 index 0000000..6b896f8 --- /dev/null +++ b/austinov.10.objects_and_classes/02.person.h @@ -0,0 +1,37 @@ +#include +#include + +namespace { using std::string; } + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here is a rather simple class definition: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +class Person +{ + private: + static const unsigned LIMIT = 25; + string lname; // Person’s last name + char fname[LIMIT]; // Person’s first name + public: + Person() { lname = ""; fname[0] = '\0'; } // #1 + Person(const string & ln, const char * fn = "Heyyou"); // #2 + // the following methods display lname and fname + void Show() const; // firstname lastname format + void FormalShow() const; // lastname, firstname format +}; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* It uses both a string object and a character array so that you */ +/* can compare how the two forms are used. */ +/* Write a program that completes the implementation by providing */ +/* code for the undefined methods. The program in which you use the */ +/* class should also use the three possible constructor calls (no */ +/* arguments, one argument, and two arguments) and the two display */ +/* methods. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + diff --git a/austinov.10.objects_and_classes/03.golf.cpp b/austinov.10.objects_and_classes/03.golf.cpp new file mode 100644 index 0000000..9ae27cc --- /dev/null +++ b/austinov.10.objects_and_classes/03.golf.cpp @@ -0,0 +1,46 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 1 from Chapter 9 but replace the code shown there */ +/* with an appropriate golf class declaration. */ +/* */ +/* Replace setgolf(golf &, const char*, int) with a constructor with */ +/* the appropriate argument for providing initial values. */ +/* */ +/* Retain the interactive version of setgolf() but implement it by */ +/* using the constructor (For example, for the code for setgolf(), */ +/* obtain the data, pass the data to the constructor to create a */ +/* temporary object and assign the temporary object to the invoking */ +/* object, which is *this.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include "03.golf.h" + +Golf::Golf(const char * name, int hc) +{ + std::strcpy(fullname, name); + handicap = hc; +} + +int Golf::set() +{ + int result = 0; + char name[Len]; + int hc = 0; + std::cout << "Please enter the name: "; + std::cin.ignore(Len, '\n'); + if (std::cin.getline(name, Len) && '\0' != name[0]) + { + std::cout << "Please enter the handicap: "; + std::cin >> hc; + *this = Golf(name, hc); + result = 1; + }; + return result; +} + +void Golf::show() const +{ + std::cout << fullname << ", " << handicap << std::endl; +} diff --git a/austinov.10.objects_and_classes/03.golf.h b/austinov.10.objects_and_classes/03.golf.h new file mode 100644 index 0000000..5f959ed --- /dev/null +++ b/austinov.10.objects_and_classes/03.golf.h @@ -0,0 +1,32 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 1 from Chapter 9 but replace the code shown there */ +/* with an appropriate golf class declaration. */ +/* */ +/* Replace setgolf(golf &, const char*, int) with a constructor with */ +/* the appropriate argument for providing initial values. */ +/* */ +/* Retain the interactive version of setgolf() but implement it by */ +/* using the constructor (For example, for the code for setgolf(), */ +/* obtain the data, pass the data to the constructor to create a */ +/* temporary object and assign the temporary object to the invoking */ +/* object, which is *this.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +class Golf +{ + private: + static const unsigned Len = 40; + char fullname[Len]; + int handicap; + + public: + Golf() { fullname[0] = '\0'; handicap = 0; } + Golf(const char * name, int hc); + int set(); + void set_hc(int hc) { handicap = hc; } + void show() const; +}; diff --git a/austinov.10.objects_and_classes/03.main.cpp b/austinov.10.objects_and_classes/03.main.cpp new file mode 100644 index 0000000..3400d8d --- /dev/null +++ b/austinov.10.objects_and_classes/03.main.cpp @@ -0,0 +1,43 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 1 from Chapter 9 but replace the code shown there */ +/* with an appropriate golf class declaration. */ +/* */ +/* Replace setgolf(golf &, const char*, int) with a constructor with */ +/* the appropriate argument for providing initial values. */ +/* */ +/* Retain the interactive version of setgolf() but implement it by */ +/* using the constructor (For example, for the code for setgolf(), */ +/* obtain the data, pass the data to the constructor to create a */ +/* temporary object and assign the temporary object to the invoking */ +/* object, which is *this.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "03.golf.h" + +int main() +{ + size_t ar_sz = 0; + std::cout << "Please enter the number of golfers: " << std::flush; + while (!(std::cin >> ar_sz)) { + while (std::cin.get() != '\n') continue; + std::cout << "Please enter the integer value: " << std::flush; + std::cin.clear(); + }; + std::cout << "You've entered " << ar_sz << std::endl; + + Golf * golfers = new Golf[ar_sz]; + + unsigned i = 0; + while (i < ar_sz && golfers[i].set()) i++; + + std::cout << std::endl << "Here are your golfers: " << std::endl; + + for (unsigned g = 0; g < i; g++) golfers[g].show(); + + delete[] golfers; + + return 0; +} + diff --git a/austinov.10.objects_and_classes/04.main.cpp b/austinov.10.objects_and_classes/04.main.cpp new file mode 100644 index 0000000..9d2055d --- /dev/null +++ b/austinov.10.objects_and_classes/04.main.cpp @@ -0,0 +1,25 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 4 from Chapter 9 but convert the Sales structure and */ +/* its associated functions to a class and its methods. Replace the */ +/* setSales(Sales &, double [], int) function with a constructor. */ +/* Implement the interactive setSales(Sales &) method by using the */ +/* constructor. Keep the class within the namespace SALES. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "04.sales.h" + +int main() +{ + + SALES::Sales sls0; + + const double arr1[] = {12.34, 56.78, 91.0, 11.12}; + SALES::Sales sls1(arr1, 4); + + sls0.show(); + sls1.show(); + + return 0; +} diff --git a/austinov.10.objects_and_classes/04.sales.cpp b/austinov.10.objects_and_classes/04.sales.cpp new file mode 100644 index 0000000..14979a7 --- /dev/null +++ b/austinov.10.objects_and_classes/04.sales.cpp @@ -0,0 +1,58 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 4 from Chapter 9 but convert the Sales structure and */ +/* its associated functions to a class and its methods. Replace the */ +/* setSales(Sales &, double [], int) function with a constructor. */ +/* Implement the interactive setSales(Sales &) method by using the */ +/* constructor. Keep the class within the namespace SALES. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "04.sales.h" + +namespace SALES +{ + Sales::Sales(const double ar[], int n = QUARTERS) + { + double mx = ar[0]; + double mn = ar[0]; + double t = 0; + for (int i = 0; i < n; i++) + { + if (ar[i] > mx) mx = ar[i]; + if (ar[i] < mn) mn = ar[i]; + t += (sales[i] = ar[i]); + }; + if (n < QUARTERS) + for (int i = n; i < QUARTERS; i++) sales[i] = 0.0; + average = t / n; + max = mx; + min = mn; + } + + Sales::Sales() + { + int len = QUARTERS; + double arr[QUARTERS]; + for (int i = 0; i < QUARTERS; i++) + { + std::cout << "Sales for quarter " << 1 + i << ": "; + if (!(std::cin >> arr[i])) + { + len = i; + break; + }; + }; + *this = Sales(arr, (QUARTERS == len) ? QUARTERS : len); + } + + void Sales::show() const + { + std::cout << "Quarterly Sales:" << std::flush; + for (unsigned i = 0; i < QUARTERS; i++) + std::cout << (0 == i ? " " : ", ") << sales[i] << std::flush; + std::cout << std::endl << "Average: " << average + << ", Max: " << max + << ", Min: " << min << std::endl; + } +} diff --git a/austinov.10.objects_and_classes/04.sales.h b/austinov.10.objects_and_classes/04.sales.h new file mode 100644 index 0000000..0cbdc50 --- /dev/null +++ b/austinov.10.objects_and_classes/04.sales.h @@ -0,0 +1,31 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 4 from Chapter 9 but convert the Sales structure and */ +/* its associated functions to a class and its methods. Replace the */ +/* setSales(Sales &, double [], int) function with a constructor. */ +/* Implement the interactive setSales(Sales &) method by using the */ +/* constructor. Keep the class within the namespace SALES. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include + +namespace SALES +{ + const int QUARTERS = 4; + + class Sales + { + private: + double sales[QUARTERS]; + double average; + double max; + double min; + public: + Sales(); + Sales(const double ar[], int n); + void show() const; + }; +} + diff --git a/austinov.10.objects_and_classes/05.main.cpp b/austinov.10.objects_and_classes/05.main.cpp new file mode 100644 index 0000000..f8cfbe5 --- /dev/null +++ b/austinov.10.objects_and_classes/05.main.cpp @@ -0,0 +1,75 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Consider the following structure declaration: */ +/* + struct customer + { + char fullname[35]; + double payment; + }; +*/ +/* Write a program that adds and removes customer structures from a */ +/* stack, represented by a Stack class declaration in listing 10.10. */ +/* Each time a customer is removed, his or her payment should be */ +/* added to a running total, and the running total should be */ +/* reported. */ +/* Note: You should be able to use the Stack class unaltered; just */ +/* change the typedef declaration so that Item is type */ +/* customerinstead of unsigned long. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// stacker.cpp -- testing the Stack class +#include +#include // or ctype.h #include "stack.h" +#include "05.stack.h" + +int main() +{ + Stack st; // create an empty stack + char ch; + customer cs; + double total = 0; + std::cout << "Please enter A to add customer," << std::endl + << "P to pop a cusromer, or Q to quit." << std::endl; + + while (std::cin >> ch && tolower(ch) != 'q') + { + while (std::cin.get() != '\n') + continue; + if (!isalpha(ch)) + { + std::cout << '\a'; + continue; + }; + switch(ch) + { + case 'A': + case 'a': + std::cout << "Enter a customer name: "; + std::cin.getline(cs.fullname, 35); + std::cout << "Enter payment: "; + std::cin >> cs.payment; + if (st.isfull()) + std::cout << "stack already full" << std::endl; + else st.push(cs); + break; + case 'P': + case 'p': + if (st.isempty()) + std::cout << "stack already empty" << std::endl; + else + { + st.pop(cs); + std::cout << "Total: " + << (total += cs.payment) << std::endl; + }; + break; + }; + std::cout << "Please enter A to add a customer," << std::endl + << "P to pop a customer, or Q to quit." << std::endl; + }; + std::cout << "Bye\n"; + return 0; +} + diff --git a/austinov.10.objects_and_classes/05.stack.cpp b/austinov.10.objects_and_classes/05.stack.cpp new file mode 100644 index 0000000..a3b49c7 --- /dev/null +++ b/austinov.10.objects_and_classes/05.stack.cpp @@ -0,0 +1,46 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Consider the following structure declaration: */ +/* + struct customer + { + char fullname[35]; + double payment; + }; +*/ +/* Write a program that adds and removes customer structures from a */ +/* stack, represented by a Stack class declaration in listing 10.10. */ +/* Each time a customer is removed, his or her payment should be */ +/* added to a running total, and the running total should be */ +/* reported. */ +/* Note: You should be able to use the Stack class unaltered; just */ +/* change the typedef declaration so that Item is type */ +/* customerinstead of unsigned long. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// Listing 10.11 stack.cpp -- Stack member functions #include "stack.h" + +#include "05.stack.h" + +bool Stack::push(const Item & item) +{ + if (top < MAX) + { + items[top++] = item; + return true; + } + else + return false; +} + +bool Stack::pop(Item & item) +{ + if (top > 0) + { + item = items[--top]; + return true; + } + else + return false; +} diff --git a/austinov.10.objects_and_classes/05.stack.h b/austinov.10.objects_and_classes/05.stack.h new file mode 100644 index 0000000..aca609d --- /dev/null +++ b/austinov.10.objects_and_classes/05.stack.h @@ -0,0 +1,50 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Consider the following structure declaration: */ + + struct customer + { + char fullname[35]; + double payment; + }; + +/* Write a program that adds and removes customer structures from a */ +/* stack, represented by a Stack class declaration in listing 10.10. */ +/* Each time a customer is removed, his or her payment should be */ +/* added to a running total, and the running total should be */ +/* reported. */ +/* Note: You should be able to use the Stack class unaltered; just */ +/* change the typedef declaration so that Item is type */ +/* customerinstead of unsigned long. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + + +// stack.h -- class definition for the stack ADT from listing 10.10 + +#ifndef STACK_H_ +#define STACK_H_ + +typedef customer Item; + +class Stack +{ + private: + enum {MAX = 10}; // constant specific to class + Item items[MAX]; // holds stack items + int top; // index for top stack item + public: + Stack() { top = 0; } // create an empty stack + bool isempty() const { return 0 == top; } + bool isfull() const { return MAX == top; } + + // push() returns false if stack already is full, + // true otherwise + bool push(const Item & item); // add item to stack + + // pop() returns false if stack already is empty, + // true otherwise + bool pop(Item & item); // pop top into item +}; + +#endif diff --git a/austinov.10.objects_and_classes/06.main.cpp b/austinov.10.objects_and_classes/06.main.cpp new file mode 100644 index 0000000..1e65312 --- /dev/null +++ b/austinov.10.objects_and_classes/06.main.cpp @@ -0,0 +1,29 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here’s a class declaration: "06.move.h" */ +/* */ +/* Create member function definitions and */ +/* a program that exercises the class. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "06.move.h" + +int main() +{ + + Move one(1.1, 1.2); + one.showmove(); + + Move two(2.1, 2.2); + two.showmove(); + + Move three = one.add(two); + three.showmove(); + + one.reset(); + one.showmove(); + + return 0; +} + diff --git a/austinov.10.objects_and_classes/06.move.cpp b/austinov.10.objects_and_classes/06.move.cpp new file mode 100644 index 0000000..f388fc9 --- /dev/null +++ b/austinov.10.objects_and_classes/06.move.cpp @@ -0,0 +1,33 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here’s a class declaration: "06.move.h" */ +/* */ +/* Create member function definitions and */ +/* a program that exercises the class. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "06.move.h" + +Move::Move(double a, double b) +{ + x = a; + y = b; +} + +void Move::reset(double a, double b) +{ + x = a; + y = b; +} + +void Move::showmove() const +{ + std::cout << "x = " << x << "; y = " << y << std::endl; +} + +Move Move::add(const Move & m) const +{ + return Move(x + m.x, y + m.y); +} + diff --git a/austinov.10.objects_and_classes/06.move.h b/austinov.10.objects_and_classes/06.move.h new file mode 100644 index 0000000..409f0d7 --- /dev/null +++ b/austinov.10.objects_and_classes/06.move.h @@ -0,0 +1,29 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Here’s a class declaration: */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +class Move +{ + private: + double x; + double y; + public: + Move(double a = 0, double b = 0); // sets x, y to a, b + void showmove() const; // shows current x, y values + Move add(const Move & m) const; + // this function adds x of m to x of invoking object to get new x, + // adds y of m to y of invoking object to get new y, creates a new + // move object initialized to new x, y values and returns it + void reset(double a = 0, double b = 0); // resets x,y to a, b +}; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Create member function definitions and */ +/* a program that exercises the class. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include diff --git a/austinov.10.objects_and_classes/07.plorg.cpp b/austinov.10.objects_and_classes/07.plorg.cpp new file mode 100644 index 0000000..3e42424 --- /dev/null +++ b/austinov.10.objects_and_classes/07.plorg.cpp @@ -0,0 +1,66 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Betelgeusean plorg has these properties: */ +/* */ +/* Data */ +/* A plorg has a name with no more than 19 letters. */ +/* A plorg has a contentment index (CI),which is an integer. */ +/* */ +/* Operations */ +/* A new plorg starts out with a name and a CI of 50. */ +/* A plorg’s CI can change. */ +/* A plorg can report its name and CI. */ +/* The default plorg has the name "Plorga". */ +/* */ +/* Write a Plorg class declaration (including data members and */ +/* member function prototypes) that represents a plorg. Write the */ +/* function definitions for the member functions. Write a short */ +/* program that demonstrates all the features of the Plorg class. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include + +class Plorg +{ + private: + std::string name; + int ci; + + public: + Plorg(std::string = "Plorga", int i = 50); + void set_ci(int ci); + void report(void); +}; + +Plorg::Plorg(std::string n, int c) +{ + name = n; + ci = c; +} + +void Plorg::set_ci(int c) +{ + ci = c; +} + +void Plorg::report(void) +{ + std::cout << "Name: " << name << ", CI: " << ci << std::endl; +} + +int main() +{ + Plorg one; + one.report(); + + Plorg another_one("Another Plorg", 42); + another_one.report(); + + one.set_ci(100500); + one.report(); + + return 0; +} + diff --git a/austinov.10.objects_and_classes/; b/austinov.10.objects_and_classes/; new file mode 100644 index 0000000..d577c78 --- /dev/null +++ b/austinov.10.objects_and_classes/; @@ -0,0 +1,31 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Do Exercise 1 from Chapter 9 but replace the code shown there */ +/* with an appropriate golf class declaration. */ +/* */ +/* Replace setgolf(golf &, const char*, int) with a constructor with */ +/* the appropriate argument for providing initial values. */ +/* */ +/* Retain the interactive version of setgolf() but implement it by */ +/* using the constructor (For example, for the code for setgolf(), */ +/* obtain the data, pass the data to the constructor to create a */ +/* temporary object and assign the temporary object to the invoking */ +/* object, which is *this.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +class Golf +{ + private: + const int Len = 40; + char fullname[Len]; + int handicap; + + public: + golf(const char * name, int hc); + int set(); + void handicap(int hc) { handicap = hc; }; + void show() const; +}; From bece4c924b14531d21291404d413a1e49ea254ff Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 2 Jul 2013 07:34:48 +0300 Subject: [PATCH 14/15] Chapter 11 Assignments --- austinov.11.working_with_classes/01.rwalk.cpp | 74 ++++++++++++ austinov.11.working_with_classes/02.vect.cpp | 110 ++++++++++++++++++ austinov.11.working_with_classes/02.vect.h | 55 +++++++++ austinov.11.working_with_classes/03.hla.cpp | 64 ++++++++++ austinov.11.working_with_classes/04.main.cpp | 22 ++++ austinov.11.working_with_classes/04.time.cpp | 64 ++++++++++ austinov.11.working_with_classes/04.time.h | 33 ++++++ austinov.11.working_with_classes/05.main.cpp | 26 +++++ .../05.stonewt.cpp | 55 +++++++++ austinov.11.working_with_classes/05.stonewt.h | 41 +++++++ austinov.11.working_with_classes/06.main.cpp | 48 ++++++++ .../06.stncmp.cpp | 60 ++++++++++ austinov.11.working_with_classes/06.stncmp.h | 46 ++++++++ austinov.11.working_with_classes/07.main.cpp | 56 +++++++++ 14 files changed, 754 insertions(+) create mode 100644 austinov.11.working_with_classes/01.rwalk.cpp create mode 100644 austinov.11.working_with_classes/02.vect.cpp create mode 100644 austinov.11.working_with_classes/02.vect.h create mode 100644 austinov.11.working_with_classes/03.hla.cpp create mode 100644 austinov.11.working_with_classes/04.main.cpp create mode 100644 austinov.11.working_with_classes/04.time.cpp create mode 100644 austinov.11.working_with_classes/04.time.h create mode 100644 austinov.11.working_with_classes/05.main.cpp create mode 100644 austinov.11.working_with_classes/05.stonewt.cpp create mode 100644 austinov.11.working_with_classes/05.stonewt.h create mode 100644 austinov.11.working_with_classes/06.main.cpp create mode 100644 austinov.11.working_with_classes/06.stncmp.cpp create mode 100644 austinov.11.working_with_classes/06.stncmp.h create mode 100644 austinov.11.working_with_classes/07.main.cpp diff --git a/austinov.11.working_with_classes/01.rwalk.cpp b/austinov.11.working_with_classes/01.rwalk.cpp new file mode 100644 index 0000000..d05b748 --- /dev/null +++ b/austinov.11.working_with_classes/01.rwalk.cpp @@ -0,0 +1,74 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Modify Listing 11.15 so that it writes the successive locations */ +/* of the random walker into a file. Label each position with the */ +/* step number. Also have the program write the initial conditions */ +/* (target distance and step size) and the summarized results to the */ +/* file. The file contents might look like this: */ +/* */ +/* Target Distance: 100, Step Size: 20 */ +/* 0: (x,y) = (0, 0) */ +/* 1: (x,y) = (-11.4715, 16.383) */ +/* 2: (x,y) = (-8.68807, -3.42232) */ +/* ... */ +/* 26: (x,y) = (42.2919, -78.2594) */ +/* 27: (x,y) = (58.6749, -89.7309) */ +/* After 27 steps, the subject has the following location: */ +/* (x, y) = (58.6749, -89.7309) */ +/* or */ +/* (m, a) = (107.212, -56.8194) */ +/* Average outward distance per step = 3.97081 */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include +#include +#include +#include "02.vect.h" + +int main() +{ + std::srand(std::time(0)); // seed random-number generator + double direction; + VECTOR::Vector step; + VECTOR::Vector result(0.0, 0.0); + unsigned long steps = 0; + double target; + double dstep; + std::ofstream fout; + fout.open("outfile.txt"); + std::cout << "Enter target distance (q to quit): "; + while (std::cin >> target) + { + std::cout << "Enter step length: "; + if (!(std::cin >> dstep)) + break; + fout << "Target distance: " << target + << ", Step Size: " << dstep << std::endl; + while (result.magval() < target) { + fout << steps << ": " << result << std::endl; + direction = std::rand() % 360; + step.reset(dstep, direction, VECTOR::Vector::POL); + result = result + step; + steps++; + }; + fout << "After " << steps << " steps, the subject " + "has the following location:\n"; + fout << result << std::endl; + result.polar_mode(); + fout << " or\n" << result << std::endl; + fout << "Average outward distance per step = " + << result.magval() / steps << std::endl; + std::cout << "Results written to outfile.txt" << std::endl; + steps = 0; + result.reset(0.0, 0.0); + std::cout << "Enter target distance (q to quit): "; + }; + std::cout << "Bye!\n"; + std::cin.clear(); + while (std::cin.get() != '\n') + continue; + return 0; +} + diff --git a/austinov.11.working_with_classes/02.vect.cpp b/austinov.11.working_with_classes/02.vect.cpp new file mode 100644 index 0000000..971388e --- /dev/null +++ b/austinov.11.working_with_classes/02.vect.cpp @@ -0,0 +1,110 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Modify the Vector class header and implementation files (Listings */ +/* 11.13 and 11.14) so that the magnitude and angle are no longer */ +/* stored as data components.Instead, they should be calculated on */ +/* demand when the magval() and angval() methods are called. */ +/* You should leave the public interface unchanged (the same public */ +/* methods with the same arguments) but alter the private section, */ +/* including some of the private method and the method */ +/* implementations. */ +/* Test the modified version with Listing 11.15, which should be */ +/* left unchanged because the public interface of the Vector class */ +/* is unchanged. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include "02.vect.h" + +namespace VECTOR +{ + const double R2D = 45.0 / std::atan(1.0); + + Vector::Vector(double n1, double n2, Mode form) + { + mode = form; + if (form == RECT) + { + x = n1; + y = n2; + } + else if (form == POL) + { + x = n1 * std::cos(n2 / R2D); + y = n1 * std::sin(n2 / R2D); + } + else + { + std::cout << "Incorrect 3rd argument to Vector() -- " + << "vector set to 0" << std::endl; + x = y = 0.0; + mode = RECT; + } + } + + void Vector::reset(double n1, double n2, Mode form) + { + mode = form; + if (form == RECT) + { + x = n1; + y = n2; + } + else if (form == POL) + { + x = n1 * std::cos(n2 / R2D); + y = n1 * std::sin(n2 / R2D); + } + else + { + std::cout << "Incorrect 3rd argument to Vector() -- " + << "vector set to 0" << std::endl; + x = y = 0.0; + mode = RECT; + } + } + + double Vector::get_mag() const + { + return std::sqrt(x * x + y * y); + } + + double Vector::get_ang() const + { + return bool(x) || bool(y) ? std::atan2(y, x) : 0.0; + } + + Vector Vector::operator+(const Vector & b) const + { + return Vector(x + b.x, y + b.y); + } + + Vector Vector::operator-(const Vector & b) const + { + return Vector(x - b.x, y - b.y); + } + + Vector Vector::operator*(double n) const + { + return Vector(n * x, n * y); + } + + Vector operator*(double n, const Vector & a) + { + return a * n; + } + + std::ostream & operator<<(std::ostream & os, const Vector & v) + { + if (v.mode == Vector::RECT) + os << "(x,y) = (" << v.x << ", " << v.y << ")"; + else if (v.mode == Vector::POL) + os << "(m,a) = (" << v.get_mag() << ", " + << v.get_ang() * R2D << ")"; + else + os << "Vector object mode is invalid"; + return os; + } +} + diff --git a/austinov.11.working_with_classes/02.vect.h b/austinov.11.working_with_classes/02.vect.h new file mode 100644 index 0000000..68ea645 --- /dev/null +++ b/austinov.11.working_with_classes/02.vect.h @@ -0,0 +1,55 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Modify the Vector class header and implementation files (Listings */ +/* 11.13 and 11.14) so that the magnitude and angle are no longer */ +/* stored as data components.Instead, they should be calculated on */ +/* demand when the magval() and angval() methods are called. */ +/* You should leave the public interface unchanged (the same public */ +/* methods with the same arguments) but alter the private section, */ +/* including some of the private method and the method */ +/* implementations. */ +/* Test the modified version with Listing 11.15, which should be */ +/* left unchanged because the public interface of the Vector class */ +/* is unchanged. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef VECTOR_H_ +#define VECTOR_H_ + +#include + +namespace VECTOR +{ + class Vector + { + public: + enum Mode {RECT, POL}; + private: + double x; + double y; + Mode mode; + double get_mag() const; + double get_ang() const; + public: + Vector() { } + ~Vector() { } + Vector(double n1, double n2, Mode form = RECT); + void reset(double n1, double n2, Mode form = RECT); + double xval() const { return x; } + double yval() const { return y; } + double magval() const { return get_mag(); } + double angval() const { return get_ang(); } + void rect_mode() { mode = RECT; } + void polar_mode() { mode = POL; } + Vector operator+(const Vector & b) const; + Vector operator-(const Vector & b) const; + Vector operator-() const { return Vector(-x, -y); } + Vector operator*(double n) const; + friend Vector operator*(double n, const Vector & a); + friend std::ostream & + operator<<(std::ostream & os, const Vector & v); + }; +} +#endif + diff --git a/austinov.11.working_with_classes/03.hla.cpp b/austinov.11.working_with_classes/03.hla.cpp new file mode 100644 index 0000000..372ba85 --- /dev/null +++ b/austinov.11.working_with_classes/03.hla.cpp @@ -0,0 +1,64 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Modify Listing 11.15 so that instead of reporting the results of */ +/* a single trial for a particular target/step combination, it */ +/* reports the highest, lowest and average number of steps for N */ +/* trials, where N is an integer entered by the user. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include +#include +#include "02.vect.h" + +int main() +{ + std::srand(std::time(0)); + double direction; + VECTOR::Vector step; + VECTOR::Vector result(0.0, 0.0); + unsigned long steps = 0; + unsigned long lowest = 0; + unsigned long highest = 0; + unsigned long total_steps = 0; + double target; + double dstep; + unsigned n = 0; + unsigned trials = 0; + std::cout << "Enter the number of trials: "; + std::cin >> n; + std::cout << "Enter target distance (q to quit): "; + while (std::cin >> target) + { + std::cout << "Enter step length: "; + if (!(std::cin >> dstep)) + break; + while (result.magval() < target) { + direction = std::rand() % 360; + step.reset(dstep, direction, VECTOR::Vector::POL); + result = result + step; + steps++; + }; + if (steps > highest) + highest = steps; + if (steps < lowest || 0 == trials) + lowest = steps; + total_steps += steps; + if (++trials >= n) + break; + steps = 0; + result.reset(0.0, 0.0); + std::cout << "Enter target distance (q to quit): "; + }; + std::cout << "Trials made: " << trials << std::endl; + std::cout << "Highest steps number: " << highest << std::endl; + std::cout << "Lowest steps number: " << lowest << std::endl; + std::cout << "Average step number: " << total_steps / trials; + std::cout << std::endl << "Bye!" << std::endl;; + std::cin.clear(); + while (std::cin.get() != '\n') + continue; + return 0; +} + diff --git a/austinov.11.working_with_classes/04.main.cpp b/austinov.11.working_with_classes/04.main.cpp new file mode 100644 index 0000000..e86d7e1 --- /dev/null +++ b/austinov.11.working_with_classes/04.main.cpp @@ -0,0 +1,22 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the final Time class example (Listings 11.10, 11.11, and */ +/* 11.12) so that all the overloaded operators are implemented using */ +/* friend functions. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "04.time.h" + +int main() +{ + Time aida(3, 35); + Time tosca(2, 48); + std::cout << "Aida and Tosca:\n"; + std::cout << aida <<"; " << tosca << std::endl; + std::cout << "Aida + Tosca: " << aida + tosca << std::endl; + std::cout << "Aida * 1.17: " << aida * 1.17 << std::endl; + std::cout << "10.0 * Tosca: " << 10.0 * tosca << std::endl; + return 0; +} + diff --git a/austinov.11.working_with_classes/04.time.cpp b/austinov.11.working_with_classes/04.time.cpp new file mode 100644 index 0000000..93b873c --- /dev/null +++ b/austinov.11.working_with_classes/04.time.cpp @@ -0,0 +1,64 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the final Time class example (Listings 11.10, 11.11, and */ +/* 11.12) so that all the overloaded operators are implemented using */ +/* friend functions. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "04.time.h" + +Time::Time(int h, int m ) +{ + hours = h; + minutes = m; +} + +void Time::AddMin(int m) +{ + minutes += m; + hours += minutes / 60; + minutes %= 60; +} + +void Time::Reset(int h, int m) +{ + hours = h; + minutes = m; +} + +Time operator+(const Time & t0, const Time & t1) +{ + Time sum; + sum.minutes = t0.minutes + t1.minutes; + sum.hours = t0.hours + t1.hours + sum.minutes / 60; + sum.minutes %= 60; + return sum; +} + +Time operator-(const Time & t0, const Time & t1) +{ + Time diff; + int tot1, tot2; + tot1 = t1.minutes + 60 * t1.hours; + tot2 = t0.minutes + 60 * t0.hours; + diff.minutes = (tot2 - tot1) % 60; + diff.hours = (tot2 - tot1) / 60; + return diff; +} + +Time operator*(const Time & t, double mult) +{ + Time result; + long totalminutes = t.hours * mult * 60 + t.minutes * mult; + result.hours = totalminutes / 60; + result.minutes = totalminutes % 60; + return result; +} + +std::ostream & operator<<(std::ostream & os, const Time & t) +{ + os << t.hours << " hours, " << t.minutes << " minutes"; + return os; +} + diff --git a/austinov.11.working_with_classes/04.time.h b/austinov.11.working_with_classes/04.time.h new file mode 100644 index 0000000..6417f0a --- /dev/null +++ b/austinov.11.working_with_classes/04.time.h @@ -0,0 +1,33 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the final Time class example (Listings 11.10, 11.11, and */ +/* 11.12) so that all the overloaded operators are implemented using */ +/* friend functions. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef MYTIME3_H_ +#define MYTIME3_H_ + +#include + +class Time +{ + private: + int hours; + int minutes; + public: + Time() { hours = minutes = 0; } + Time(int h, int m = 0); + void AddMin(int m); + void AddHr(int h) { hours += h; } + void Reset(int h = 0, int m = 0); + friend Time operator+(const Time & t0, const Time & t1); + friend Time operator-(const Time & t0, const Time & t1); + friend Time operator*(const Time & t, double n); + friend Time operator*(double m, const Time & t) { return t * m; } + friend std::ostream & operator<<(std::ostream & os, const Time & t); +}; + +#endif + diff --git a/austinov.11.working_with_classes/05.main.cpp b/austinov.11.working_with_classes/05.main.cpp new file mode 100644 index 0000000..c21b715 --- /dev/null +++ b/austinov.11.working_with_classes/05.main.cpp @@ -0,0 +1,26 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the Stonewt class (Listings 11.16 and 11.17) so that it */ +/* has a state member that governs whether the object is interpreted */ +/* in stone form, integer pounds form, or floating-point pounds form */ +/* Overload the < + +class Stonewt +{ + public: + enum State {STN, LBS, FLT}; + private: + enum {Lbs_per_stn = 14}; + int stone; + double pds_left; + double pounds; + State st; + public: + Stonewt(double lbs); + Stonewt(int stn, double lbs); + Stonewt() { stone = pounds = pds_left = 0; } + ~Stonewt() {} + void set_st(State s) { st = s; } + Stonewt operator+(const Stonewt & s) const; + Stonewt operator-(const Stonewt & s) const; + Stonewt operator*(const Stonewt & s) const; + friend std::ostream & operator<<(std::ostream & o, const Stonewt & s); +}; +#endif + diff --git a/austinov.11.working_with_classes/06.main.cpp b/austinov.11.working_with_classes/06.main.cpp new file mode 100644 index 0000000..3c5adbb --- /dev/null +++ b/austinov.11.working_with_classes/06.main.cpp @@ -0,0 +1,48 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the Stonewt class (Listings 11.16 and 11.17) so that it */ +/* overloads all six relational operators. The operators should */ +/* compare the pounds members and return a type bool value. Write a */ +/* program that declares an array of six Stonewt objects and */ +/* initializes the first three objects in the array declaration. */ +/* Then it should use a loop to read in values used to set the */ +/* remaining three array elements. Then it should report the */ +/* smallest element, the largest element, and how many elements are */ +/* greater or equal to 11 stone. (The simplest approach is to create */ +/* a Stonewt object initialized to 11 stone and to compare the other */ +/* objects with that object.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "06.stncmp.h" +#include + +int main() +{ + std::array arrostn = {Stonewt(12,3), + Stonewt(13,4), + Stonewt(14.99)}; + + for (unsigned i = 3; i < 6; i++) + { + std::cout << "Please enter the weight: "; + std::cin >> arrostn[i]; + }; + + Stonewt smallest = 0; + Stonewt largest = 0; + Stonewt stone11 = Stonewt(11, 0); + unsigned counter = 0; + + for (unsigned i = 0; i < 6; i++) + { + if (arrostn[i] > largest) largest = arrostn[i]; + if (arrostn[i] < smallest || 0 == i) smallest = arrostn[i]; + if (arrostn[i] >= stone11) counter++; + }; + + std::cout << "The smallest is " << smallest; + std::cout << "The largest is " << largest; + std::cout << counter << " are greater than 11 stone;" << std::endl; +} + diff --git a/austinov.11.working_with_classes/06.stncmp.cpp b/austinov.11.working_with_classes/06.stncmp.cpp new file mode 100644 index 0000000..971ac96 --- /dev/null +++ b/austinov.11.working_with_classes/06.stncmp.cpp @@ -0,0 +1,60 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the Stonewt class (Listings 11.16 and 11.17) so that it */ +/* overloads all six relational operators. The operators should */ +/* compare the pounds members and return a type bool value. Write a */ +/* program that declares an array of six Stonewt objects and */ +/* initializes the first three objects in the array declaration. */ +/* Then it should use a loop to read in values used to set the */ +/* remaining three array elements. Then it should report the */ +/* smallest element, the largest element, and how many elements are */ +/* greater or equal to 11 stone. (The simplest approach is to create */ +/* a Stonewt object initialized to 11 stone and to compare the other */ +/* objects with that object.) */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "06.stncmp.h" + +Stonewt::Stonewt(double lbs) +{ + stone = int (lbs) / Lbs_per_stn; + pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs); + pounds = lbs; + st = LBS; +} + +Stonewt::Stonewt(int stn, double lbs) +{ + stone = stn; + pds_left = lbs; + pounds = stn * Lbs_per_stn + lbs; + st = STN; +} + +bool Stonewt::operator>(const Stonewt & s) const {return pounds > s.pounds;} +bool Stonewt::operator<(const Stonewt & s) const {return pounds < s.pounds;} + +bool Stonewt::operator>=(const Stonewt & s) const {return pounds >= s.pounds;} +bool Stonewt::operator<=(const Stonewt & s) const {return pounds <= s.pounds;} + +bool Stonewt::operator==(const Stonewt & s) const {return pounds == s.pounds;} +bool Stonewt::operator!=(const Stonewt & s) const {return pounds != s.pounds;} + +std::ostream & operator<<(std::ostream & o, const Stonewt & s) +{ + if (Stonewt::STN == s.st) + o << s.stone << " stone, " << s.pds_left << " pounds" << std::endl; + if (Stonewt::LBS == s.st) + o << s.pounds << " pounds" << std::endl; + return o; +} + +std::istream & operator>>(std::istream & istr, Stonewt & s) +{ + double lbs; + istr >> lbs; + s = Stonewt(lbs); + return istr; +} + diff --git a/austinov.11.working_with_classes/06.stncmp.h b/austinov.11.working_with_classes/06.stncmp.h new file mode 100644 index 0000000..ee9ce0f --- /dev/null +++ b/austinov.11.working_with_classes/06.stncmp.h @@ -0,0 +1,46 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* Rewrite the Stonewt class (Listings 11.16 and 11.17) so that it */ +/* overloads all six relational operators. The operators should */ +/* compare the pounds members and return a type bool value. Write a */ +/* program that declares an array of six Stonewt objects and */ +/* initializes the first three objects in the array declaration. */ +/* Then it should use a loop to read in values used to set the */ +/* remaining three array elements. Then it should report the */ +/* smallest element, the largest element, and how many elements are */ +/* greater or equal to 11 stone. (The simplest approach is to create */ +/* a Stonewt object initialized to 11 stone and to compare the other */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#ifndef STNCMP_H_ +#define STNCMP_H_ + +#include + +class Stonewt +{ + private: + enum {Lbs_per_stn = 14}; + enum State {STN, LBS, FLT}; + int stone; + double pds_left; + double pounds; + State st; + public: + Stonewt(double lbs); + Stonewt(int stn, double lbs); + Stonewt() { stone = pounds = pds_left = 0; } + ~Stonewt() {} + void set_st(State s) { st = s; } + bool operator>(const Stonewt & s) const; + bool operator<(const Stonewt & s) const; + bool operator>=(const Stonewt & s) const; + bool operator<=(const Stonewt & s) const; + bool operator==(const Stonewt & s) const; + bool operator!=(const Stonewt & s) const; + friend std::ostream & operator<<(std::ostream & o, const Stonewt & s); + friend std::istream & operator>>(std::istream & istr, Stonewt & s); +}; +#endif + diff --git a/austinov.11.working_with_classes/07.main.cpp b/austinov.11.working_with_classes/07.main.cpp new file mode 100644 index 0000000..dac8e26 --- /dev/null +++ b/austinov.11.working_with_classes/07.main.cpp @@ -0,0 +1,56 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* A complex number has two parts: a real part and an imaginary part */ +/* One way to write an imaginary number is this: (3.0,4.0). Here 3.0 */ +/* is the real part and 4.0 is the imaginary part. Suppose a=(A,Bi) */ +/* and c = (C,Di). Here are some complex operations: */ +/* * Addition: a + c = (A + C,(B + D)i) */ +/* * Subtraction: a - c = (A - C,(B - D)i) */ +/* * Multiplication: a ×c = (A ×C - B×D,(A×D + B×C)i) */ +/* * Multiplication: (x a real number):x ×c = (x×C,x×Di) */ +/* * Conjugation: ~a = (A,- Bi) */ +/* Define a complex class so that the following program can use it */ +/* with correct results: */ + +#include +using namespace std; +#include "complex0.h" // to avoid confusion with complex.h +int main() +{ + complex a(3.0, 4.0); // initialize to (3,4i) complex c; + cout << "Enter a complex number (q to quit):\n"; + while (cin >> c) + { + cout << "c is " << c << '\n'; + cout << "complex conjugate is " << ~c << '\n'; + cout << "a is " << a << '\n"; + cout << "a + c is " << a + c << '\n'; + cout << "a - c is " << a - c << '\n'; + cout << "a * c is " << a * c<< '\n'; + cout << "2 * c is " << 2 * c << '\n'; + cout << "Enter a complex number (q to quit):\n"; + } + cout << "Done!\n"; + return 0; +} + +/* Note that you have to overload the << and >> operators. Standard */ +/* C++ already has complex support, rather more extensive than in */ +/* this example — in a complex header file, so use complex0.h to */ +/* avoid conflicts. Use const whenever warranted. Here is a sample */ +/* run of the program: */ +/* Enter a complex number (q to quit): */ +/* real:10 */ +/* imaginary:12 */ +/* c is (10,12i) */ +/* complex conjugate is (10,-12i) */ +/* a is (3,4i) */ +/* a + c is (13,16i) */ +/* a - c is (-7,-8i) */ +/* a * c is (-18,76i) */ +/* 2 * c is (20,24i) */ +/* Enter a complex number (q to quit): */ +/* real:q */ +/* Done! */ +/* Note that cin >> c, through overloading, now prompts for real */ +/* and imaginary parts. */ From 6e780bd3bef753efde8edcbadf25f6cfaeb99d21 Mon Sep 17 00:00:00 2001 From: Artem Ustinov Date: Tue, 2 Jul 2013 11:32:10 +0300 Subject: [PATCH 15/15] Chapter 11 Assignment 7 --- austinov.11.working_with_classes/07.cmplx.cpp | 82 +++++++++++++++++++ austinov.11.working_with_classes/07.cmplx.h | 60 ++++++++++++++ austinov.11.working_with_classes/07.main.cpp | 40 +++++---- 3 files changed, 164 insertions(+), 18 deletions(-) create mode 100644 austinov.11.working_with_classes/07.cmplx.cpp create mode 100644 austinov.11.working_with_classes/07.cmplx.h diff --git a/austinov.11.working_with_classes/07.cmplx.cpp b/austinov.11.working_with_classes/07.cmplx.cpp new file mode 100644 index 0000000..022c879 --- /dev/null +++ b/austinov.11.working_with_classes/07.cmplx.cpp @@ -0,0 +1,82 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* A complex number has two parts: a real part and an imaginary part */ +/* One way to write an imaginary number is this: (3.0,4.0). Here 3.0 */ +/* is the real part and 4.0 is the imaginary part. Suppose a=(A,Bi) */ +/* and c = (C,Di). Here are some complex operations: */ +/* * Addition: a + c = (A + C,(B + D)i) */ +/* * Subtraction: a - c = (A - C,(B - D)i) */ +/* * Multiplication: a × c = (A × C - B × D, (A × D + B × C)i) */ +/* * Multiplication: (x a real number): x × c = (x × C, x × Di) */ +/* * Conjugation: ~a = (A,- Bi) */ +/* Define a complex class so that the following program can use it */ +/* with correct results: see 07.main.cpp */ +/* */ +/* Note that you have to overload the << and >> operators. Standard */ +/* C++ already has complex support, rather more extensive than in */ +/* this example — in a complex header file, so use complex0.h to */ +/* avoid conflicts. Use const whenever warranted. Here is a sample */ +/* run of the program: */ +/* */ +/* Enter a complex number (q to quit): */ +/* real:10 */ +/* imaginary:12 */ +/* c is (10,12i) */ +/* complex conjugate is (10,-12i) */ +/* a is (3,4i) */ +/* a + c is (13,16i) */ +/* a - c is (-7,-8i) */ +/* a * c is (-18,76i) */ +/* 2 * c is (20,24i) */ +/* Enter a complex number (q to quit): */ +/* real:q */ +/* Done! */ +/* */ +/* Note that cin >> c, through overloading, now prompts for real */ +/* and imaginary parts. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "07.cmplx.h" + +Complex Complex::operator~() const +{ + return Complex(r, -i); +} + +Complex Complex::operator+(const Complex & cn) const +{ + return Complex(r + cn.r, i + cn.i); +} + +Complex Complex::operator-(const Complex & cn) const +{ + return Complex(r - cn.r, i - cn.i); +} + +Complex Complex::operator*(const Complex & cn) const +{ + return Complex(r * cn.r - i * cn.i, + r * cn.i + i * cn.r); +} + +Complex Complex::operator*(double n) const +{ + return Complex(r * n, i * n); +} + +std::istream & operator>>(std::istream & istrm, Complex & cn) +{ + std::cout << "real: "; + istrm >> cn.r; + std::cout << "imaginary: "; + istrm >> cn.i; + return istrm; +} + +std::ostream & operator<<(std::ostream & ostrm, const Complex & cn) +{ + ostrm << "(" << cn.r << ", " << cn.i << "i)"; + return ostrm; +} + diff --git a/austinov.11.working_with_classes/07.cmplx.h b/austinov.11.working_with_classes/07.cmplx.h new file mode 100644 index 0000000..151d865 --- /dev/null +++ b/austinov.11.working_with_classes/07.cmplx.h @@ -0,0 +1,60 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ +/* */ +/* A complex number has two parts: a real part and an imaginary part */ +/* One way to write an imaginary number is this: (3.0,4.0). Here 3.0 */ +/* is the real part and 4.0 is the imaginary part. Suppose a=(A,Bi) */ +/* and c = (C,Di). Here are some complex operations: */ +/* * Addition: a + c = (A + C,(B + D)i) */ +/* * Subtraction: a - c = (A - C,(B - D)i) */ +/* * Multiplication: a ×c = (A ×C - B×D,(A×D + B×C)i) */ +/* * Multiplication: (x a real number):x ×c = (x×C,x×Di) */ +/* * Conjugation: ~a = (A,- Bi) */ +/* Define a complex class so that the following program can use it */ +/* with correct results: see 07.main.cpp */ +/* */ +/* Note that you have to overload the << and >> operators. Standard */ +/* C++ already has complex support, rather more extensive than in */ +/* this example — in a complex header file, so use complex0.h to */ +/* avoid conflicts. Use const whenever warranted. Here is a sample */ +/* run of the program: */ +/* */ +/* Enter a complex number (q to quit): */ +/* real:10 */ +/* imaginary:12 */ +/* c is (10,12i) */ +/* complex conjugate is (10,-12i) */ +/* a is (3,4i) */ +/* a + c is (13,16i) */ +/* a - c is (-7,-8i) */ +/* a * c is (-18,76i) */ +/* 2 * c is (20,24i) */ +/* Enter a complex number (q to quit): */ +/* real:q */ +/* Done! */ +/* */ +/* Note that cin >> c, through overloading, now prompts for real */ +/* and imaginary parts. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include + +class Complex +{ + private: + double r; + double i; + public: + Complex() { r = 0; i = 0; } + Complex(double real, double imaginary) { r = real; i = imaginary; } + Complex operator~() const; + Complex operator+(const Complex & cn) const; + Complex operator-(const Complex & cn) const; + Complex operator*(const Complex & cn) const; + Complex operator*(double n) const; + friend Complex operator*(double n, Complex & cn) { return cn * n; } + friend std::istream & operator>>(std::istream & istrm, Complex & cn); + friend std::ostream & operator<<(std::ostream & ostrm, + const Complex & cn); +}; + diff --git a/austinov.11.working_with_classes/07.main.cpp b/austinov.11.working_with_classes/07.main.cpp index dac8e26..032d23e 100644 --- a/austinov.11.working_with_classes/07.main.cpp +++ b/austinov.11.working_with_classes/07.main.cpp @@ -12,25 +12,25 @@ /* Define a complex class so that the following program can use it */ /* with correct results: */ -#include -using namespace std; -#include "complex0.h" // to avoid confusion with complex.h +#include "07.cmplx.h" // to avoid confusion with complex.h + int main() { - complex a(3.0, 4.0); // initialize to (3,4i) complex c; - cout << "Enter a complex number (q to quit):\n"; - while (cin >> c) + Complex a(3.0, 4.0); // initialize to (3,4i) + Complex c; + std::cout << "Enter a complex number (q to quit):" << std::endl; + while (std::cin >> c) { - cout << "c is " << c << '\n'; - cout << "complex conjugate is " << ~c << '\n'; - cout << "a is " << a << '\n"; - cout << "a + c is " << a + c << '\n'; - cout << "a - c is " << a - c << '\n'; - cout << "a * c is " << a * c<< '\n'; - cout << "2 * c is " << 2 * c << '\n'; - cout << "Enter a complex number (q to quit):\n"; + std::cout << "c is " << c << std::endl; + std::cout << "complex conjugate is " << ~c << std::endl; + std::cout << "a is " << a << std::endl; + std::cout << "a + c is " << a + c << std::endl; + std::cout << "a - c is " << a - c << std::endl; + std::cout << "a * c is " << a * c << std::endl; + std::cout << "2 * c is " << 2 * c << std::endl; + std::cout << "Enter a complex number (q to quit):" << std::endl; } - cout << "Done!\n"; + std::cout << "Done!" << std::endl; return 0; } @@ -39,6 +39,7 @@ int main() /* this example — in a complex header file, so use complex0.h to */ /* avoid conflicts. Use const whenever warranted. Here is a sample */ /* run of the program: */ +/* */ /* Enter a complex number (q to quit): */ /* real:10 */ /* imaginary:12 */ @@ -50,7 +51,10 @@ int main() /* a * c is (-18,76i) */ /* 2 * c is (20,24i) */ /* Enter a complex number (q to quit): */ -/* real:q */ +/* real:q */ /* Done! */ -/* Note that cin >> c, through overloading, now prompts for real */ -/* and imaginary parts. */ +/* */ +/* Note that cin >> c, through overloading, now prompts for real and */ +/* imaginary parts. */ +/* */ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */