diff --git a/SourceCode/Appendix F/PrF-1.cpp b/SourceCode/Appendix F/PrF-1.cpp new file mode 100755 index 0000000..d98756c --- /dev/null +++ b/SourceCode/Appendix F/PrF-1.cpp @@ -0,0 +1,19 @@ +// Demonstrates a simple namespace +#include +using namespace std; + +namespace test +{ +int x, y, z; +} + +int main() +{ + test::x = 10; + test::y = 20; + test::z = 30; + cout << "The values are:\n"; + cout << test::x << " " << test::y + << " " << test::z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix F/PrF-2.cpp b/SourceCode/Appendix F/PrF-2.cpp new file mode 100755 index 0000000..a60fa7b --- /dev/null +++ b/SourceCode/Appendix F/PrF-2.cpp @@ -0,0 +1,30 @@ +// Demonstrates two namespaces +#include +using namespace std; + +namespace test1 +{ + int x, y, z; +} + +namespace test2 +{ + int x, y, z; +} + +int main() +{ + test1::x = 10; + test1::y = 20; + test1::z = 30; + cout << "The test1 values are:\n"; + cout << test1::x << " " << test1::y + << " " << test1::z << endl; + test2::x = 1; + test2::y = 2; + test2::z = 3; + cout << "The test2 values are:\n"; + cout << test2::x << " " << test2::y + << " " << test2::z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix F/PrF-3.cpp b/SourceCode/Appendix F/PrF-3.cpp new file mode 100755 index 0000000..7117485 --- /dev/null +++ b/SourceCode/Appendix F/PrF-3.cpp @@ -0,0 +1,17 @@ +// A demonstration of the using namespace statement. +#include +#include "nsdemo.h" +using namespace std; +using namespace demo; + +int main() +{ + testObject.x = 10; + testObject.y = 20; + testObject.z = 30; + cout << "The values are:\n" + << testObject.x << " " + << testObject.y << " " + << testObject.z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix F/nsdemo.h b/SourceCode/Appendix F/nsdemo.h new file mode 100755 index 0000000..51d2997 --- /dev/null +++ b/SourceCode/Appendix F/nsdemo.h @@ -0,0 +1,15 @@ +// This file defines a namespace named demo. +// In the demo namespace a class named NsDemo +// is declared, and an instance of the class +// named testObject is defined. + +namespace demo +{ + class NsDemo + { + public: + int x, y, z; + }; + + NsDemo testObject; +} \ No newline at end of file diff --git a/SourceCode/Appendix G/argdemo.cpp b/SourceCode/Appendix G/argdemo.cpp new file mode 100755 index 0000000..e5bf3e1 --- /dev/null +++ b/SourceCode/Appendix G/argdemo.cpp @@ -0,0 +1,17 @@ +// This program demonstrates how to read +// command line arguments. +#include +using namespace std; + +int main(int argc, char *argv[]) +{ + cout << "You entered " << (argc - 1); + cout << " command line arguments.\n"; + if (argc > 1) + { + cout << "Here they are:\n"; + for (int count = 1; count < argc; count++) + cout << argv[count] << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix G/sum.cpp b/SourceCode/Appendix G/sum.cpp new file mode 100755 index 0000000..454455f --- /dev/null +++ b/SourceCode/Appendix G/sum.cpp @@ -0,0 +1,18 @@ +// This program takes two command line arguments, +// assumed to be numbers, and displays their sum. +#include +#include // Needed for atof +using namespace std; + +int main(int argc, char *argv[]) +{ + double total = 0; + + if (argc > 1) + { + for (int count = 1; count < argc; count++) + total += atof(argv[count]); + cout << total << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix J/Pet.cpp b/SourceCode/Appendix J/Pet.cpp new file mode 100755 index 0000000..ed021aa --- /dev/null +++ b/SourceCode/Appendix J/Pet.cpp @@ -0,0 +1,16 @@ +// Pet class implementation file +#include +#include "Pet.h" +using namespace std; + +// Constructor +Pet::Pet(string str) +{ + name = str; +} + +// getName member function +string Pet::getName() const +{ + return name; +} diff --git a/SourceCode/Appendix J/Pet.h b/SourceCode/Appendix J/Pet.h new file mode 100755 index 0000000..f20cacd --- /dev/null +++ b/SourceCode/Appendix J/Pet.h @@ -0,0 +1,20 @@ +// Pet class specification file +#ifndef PET_H +#define PET_H +#include +using namespace std; + +class Pet +{ +private: + string name; // To hold the pet's name + +public: + // Constructor + Pet(string); + + // Accessor function for name + string getName() const; +}; + +#endif diff --git a/SourceCode/Appendix J/PrJ-1.cpp b/SourceCode/Appendix J/PrJ-1.cpp new file mode 100755 index 0000000..2d9190e --- /dev/null +++ b/SourceCode/Appendix J/PrJ-1.cpp @@ -0,0 +1,13 @@ +#include +#include "Pet.h" +using namespace std; + +int main() +{ + // Create an instance of the Pet class. + Pet myPet("Fido"); + + // Display my pet's name. + cout << "My pet's name is " << myPet.getName() << endl; + return 0; +} diff --git a/SourceCode/Appendix J/PrJ-2.cpp b/SourceCode/Appendix J/PrJ-2.cpp new file mode 100755 index 0000000..c027d25 --- /dev/null +++ b/SourceCode/Appendix J/PrJ-2.cpp @@ -0,0 +1,34 @@ +// This program uses the Rectangle class, which is declared in +// the Rectangle.h file. The Rectangle class's member functions +// are defined in the Rectangle.cpp file. This program should +// be compiled with those files in a project. +#include +#include "Rectangle.h" // Needed for Rectangle class +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + double rectWidth; // Local variable for width + double rectLength; // Local variable for length + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + // Store the width and length of the rectangle + // in the box object. + box.setWidth(rectWidth); + box.setLength(rectLength); + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + + return 0; +} diff --git a/SourceCode/Appendix J/Rectangle.cpp b/SourceCode/Appendix J/Rectangle.cpp new file mode 100755 index 0000000..a962792 --- /dev/null +++ b/SourceCode/Appendix J/Rectangle.cpp @@ -0,0 +1,62 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// getWidth returns the value in the member variable width. * +//*********************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//************************************************************* +// getLength returns the value in the member variable length. * +//************************************************************* + +double Rectangle::getLength() const +{ + return length; +} + +//************************************************************ +// getArea returns the product of width times length. * +//************************************************************ + +double Rectangle::getArea() const +{ + return width * length; +} \ No newline at end of file diff --git a/SourceCode/Appendix J/Rectangle.h b/SourceCode/Appendix J/Rectangle.h new file mode 100755 index 0000000..ed481b4 --- /dev/null +++ b/SourceCode/Appendix J/Rectangle.h @@ -0,0 +1,20 @@ +// Specification file for the Rectangle class. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +// Rectangle class declaration. + +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +#endif diff --git a/SourceCode/Appendix J/RectangleData.cpp b/SourceCode/Appendix J/RectangleData.cpp new file mode 100755 index 0000000..cdd7eed --- /dev/null +++ b/SourceCode/Appendix J/RectangleData.cpp @@ -0,0 +1,33 @@ +// This program uses the Rectangle class's specification +// and implementation files. +#include +#include "Rectangle.h" // Contains the class declaration. +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the class. + float rectWidth, // Local varibale for width. + rectLength; // Local variable for length. + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + if (!box.setWidth(rectWidth)) // Store the width. + cout << "Invalid value for width.\n"; + else if (!box.setLength(rectLength)) // Store the length. + cout << "Invalid value for length.\n"; + else + { + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + } + return 0; +} diff --git a/SourceCode/Appendix K/PrK-1.cpp b/SourceCode/Appendix K/PrK-1.cpp new file mode 100755 index 0000000..8f6d4bc --- /dev/null +++ b/SourceCode/Appendix K/PrK-1.cpp @@ -0,0 +1,31 @@ +// This program asks for sales figures for 3 days. The total +// sales is calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + total = day1 + day2 + day3; + + cout.precision(2); + cout.setf(ios::fixed | ios::showpoint); + + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix K/PrK-2.cpp b/SourceCode/Appendix K/PrK-2.cpp new file mode 100755 index 0000000..f34de41 --- /dev/null +++ b/SourceCode/Appendix K/PrK-2.cpp @@ -0,0 +1,14 @@ +// This program uses cin's width member function. +#include +using namespace std; + +int main() +{ + char word[5]; + + cout << "Enter a word: "; + cin.width(5); + cin >> word; + cout << "You entered " << word << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix K/PrK-3.cpp b/SourceCode/Appendix K/PrK-3.cpp new file mode 100755 index 0000000..89eff61 --- /dev/null +++ b/SourceCode/Appendix K/PrK-3.cpp @@ -0,0 +1,27 @@ +// This program uses the precision member function of a +// file stream object to format file output. +#include +#include +using namespace std; + +int main() +{ + fstream dataFile; + double num = 123.456; + + // Open the file. + dataFile.open("numfile.txt", ios::out); + + // Write a value at various digits of precision + dataFile << num << endl; + dataFile.precision(5); + dataFile << num << endl; + dataFile.precision(4); + dataFile << num << endl; + dataFile.precision(3); + dataFile << num << endl; + + // Close the file. + dataFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Appendix K/numfile.txt b/SourceCode/Appendix K/numfile.txt new file mode 100755 index 0000000..4b2128f --- /dev/null +++ b/SourceCode/Appendix K/numfile.txt @@ -0,0 +1,4 @@ +123.456 +123.46 +123.5 +123 \ No newline at end of file diff --git a/SourceCode/Chapter 01/Pr1-1.cpp b/SourceCode/Chapter 01/Pr1-1.cpp new file mode 100755 index 0000000..f4efad8 --- /dev/null +++ b/SourceCode/Chapter 01/Pr1-1.cpp @@ -0,0 +1,23 @@ +// This progam calculates the user's pay. +#include +using namespace std; + +int main() +{ + double hours, rate, pay; + + // Get the number of hours worked. + cout << "How many hours did you work? "; + cin >> hours; + + // Get the hourly pay rate. + cout << "How much do you get paid per hour? "; + cin >> rate; + + // Calculate the pay. + pay = hours * rate; + + // Display the pay. + cout << "You have earned $" << pay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-1.cpp b/SourceCode/Chapter 02/Pr2-1.cpp new file mode 100755 index 0000000..b4b174b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-1.cpp @@ -0,0 +1,9 @@ +// A simple C++ program +#include +using namespace std; + +int main() +{ + cout << "Programming is great fun!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-10.cpp b/SourceCode/Chapter 02/Pr2-10.cpp new file mode 100755 index 0000000..1f250d8 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-10.cpp @@ -0,0 +1,20 @@ +// This program has variables of several of the integer types. +#include +using namespace std; + +int main() +{ + int checking; + unsigned int miles; + long days; + + checking = -20; + miles = 4276; + days = 189000; + cout << "We have made a long journey of " << miles; + cout << " miles.\n"; + cout << "Our checking account balance is " << checking; + cout << "\nAbout " << days << " days ago Columbus "; + cout << "stood on this spot.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-11.cpp b/SourceCode/Chapter 02/Pr2-11.cpp new file mode 100755 index 0000000..6af16e8 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-11.cpp @@ -0,0 +1,16 @@ +// This program shows three variables defined on the same line. +#include +using namespace std; + +int main() +{ + int floors, rooms, suites; + + floors = 15; + rooms = 300; + suites = 30; + cout << "The Grande Hotel has " << floors << " floors\n"; + cout << "with " << rooms << " rooms and " << suites; + cout << " suites.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-12.cpp b/SourceCode/Chapter 02/Pr2-12.cpp new file mode 100755 index 0000000..efa5f44 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-12.cpp @@ -0,0 +1,14 @@ +// This program works with characters. +#include +using namespace std; + +int main() +{ + char letter; + + letter = 'A'; + cout << letter << endl; + letter = 'B'; + cout << letter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-13.cpp b/SourceCode/Chapter 02/Pr2-13.cpp new file mode 100755 index 0000000..965508b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-13.cpp @@ -0,0 +1,15 @@ +// This program demonstrates the close relationship between +// characters and integers. +#include +using namespace std; + +int main() +{ + char letter; + + letter = 65; + cout << letter << endl; + letter = 66; + cout << letter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-14.cpp b/SourceCode/Chapter 02/Pr2-14.cpp new file mode 100755 index 0000000..cbc96d0 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-14.cpp @@ -0,0 +1,14 @@ +// This program uses character literals. +#include +using namespace std; + +int main() +{ + char letter; + + letter = 'A'; + cout << letter << '\n'; + letter = 'B'; + cout << letter << '\n'; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-15.cpp b/SourceCode/Chapter 02/Pr2-15.cpp new file mode 100755 index 0000000..68dd49c --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-15.cpp @@ -0,0 +1,13 @@ +// This program demonstrates the string class. +#include +#include // Required for the string class. +using namespace std; + +int main() +{ + string movieTitle; + + movieTitle = "Wheels of Fury"; + cout << "My favorite movie is " << movieTitle << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-16.cpp b/SourceCode/Chapter 02/Pr2-16.cpp new file mode 100755 index 0000000..5a9ebc5 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-16.cpp @@ -0,0 +1,15 @@ +// This program uses floating point data types. +#include +using namespace std; + +int main() +{ + float distance; + double mass; + + distance = 1.495979E11; + mass = 1.989E30; + cout << "The Sun is " << distance << " meters away.\n"; + cout << "The Sun\'s mass is " << mass << " kilograms.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-17.cpp b/SourceCode/Chapter 02/Pr2-17.cpp new file mode 100755 index 0000000..58d3f0e --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-17.cpp @@ -0,0 +1,14 @@ +// This program demonstrates boolean variables. +#include +using namespace std; + +int main() +{ + bool boolValue; + + boolValue = true; + cout << boolValue << endl; + boolValue = false; + cout << boolValue << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-18.cpp b/SourceCode/Chapter 02/Pr2-18.cpp new file mode 100755 index 0000000..3f8d7df --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-18.cpp @@ -0,0 +1,17 @@ +// This program determines the size of integers, long +// integers, and long doubles. +#include +using namespace std; + +int main() +{ + long double apple; + + cout << "The size of an integer is " << sizeof(int); + cout << " bytes.\n"; + cout << "The size of a long integer is " << sizeof(long); + cout << " bytes.\n"; + cout << "An apple can be eaten in " << sizeof(apple); + cout << " bytes!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-19.cpp b/SourceCode/Chapter 02/Pr2-19.cpp new file mode 100755 index 0000000..e45a747 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-19.cpp @@ -0,0 +1,11 @@ +// This program shows variable initialization. +#include +using namespace std; + +int main() +{ + int month = 2, days = 28; + + cout << "Month " << month << " has " << days << " days.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-2.cpp b/SourceCode/Chapter 02/Pr2-2.cpp new file mode 100755 index 0000000..2999954 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-2.cpp @@ -0,0 +1,9 @@ +// A simple C++ program +#include +using namespace std; + +int main() +{ + cout << "Programming is " << "great fun!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-20.cpp b/SourceCode/Chapter 02/Pr2-20.cpp new file mode 100755 index 0000000..c75035f --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-20.cpp @@ -0,0 +1,11 @@ +// This program can't find its variable. +#include +using namespace std; + +int main() +{ + cout << value; // ERROR! value not defined yet! + + int value = 100; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-21.cpp b/SourceCode/Chapter 02/Pr2-21.cpp new file mode 100755 index 0000000..6362f93 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-21.cpp @@ -0,0 +1,27 @@ +// This program calculates hourly wages, including overtime. +#include +using namespace std; + +int main() +{ + double regularWages, // To hold regular wages + basePayRate = 18.25, // Base pay rate + regularHours = 40.0, // Hours worked less overtime + overtimeWages, // To hold overtime wages + overtimePayRate = 27.78, // Overtime pay rate + overtimeHours = 10, // Overtime hours worked + totalWages; // To hold total wages + + // Calculate the regular wages. + regularWages = basePayRate * regularHours; + + // Calculate the overtime wages. + overtimeWages = overtimePayRate * overtimeHours; + + // Calculate the total wages. + totalWages = regularWages + overtimeWages; + + // Display the total wages. + cout << "Wages for this week are $" << totalWages << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-22.cpp b/SourceCode/Chapter 02/Pr2-22.cpp new file mode 100755 index 0000000..46a6f64 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-22.cpp @@ -0,0 +1,29 @@ +// This program calculates the amount of pay that will +// be contributed to a retirement plan if 5%, 7%, or 10% +// of monthly pay is withheld. +#include +using namespace std; + +int main() +{ + // Variables to hold the monthly pay and the + // amount of contribution. + double monthlyPay = 6000.0, contribution; + + // Calculate and display a 5% contribution. + contribution = monthlyPay * 0.05; + cout << "5 percent is $" << contribution + << " per month.\n"; + + // Calculate and display a 7% contribution. + contribution = monthlyPay * 0.07; + cout << "7 percent is $" << contribution + << " per month.\n"; + + // Calculate and display a 10% contribution. + contribution = monthlyPay * 0.1; + cout << "10 percent is $" << contribution + << " per month.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-23.cpp b/SourceCode/Chapter 02/Pr2-23.cpp new file mode 100755 index 0000000..c6f8c8d --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-23.cpp @@ -0,0 +1,25 @@ +// This program calculates the sale price of an item +// that is regularly priced at $59.95, with a 20 percent +// discount subtracted. +#include +using namespace std; + +int main() +{ + // Variables to hold the regular price, the + // amount of a discount, and the sale price. + double regularPrice = 59.95, discount, salePrice; + + // Calculate the amount of a 20% discount. + discount = regularPrice * 0.20; + + // Calculate the sale price by subtracting the + // discount from the regular price. + salePrice = regularPrice - discount; + + // Display the results. + cout << "Regular price: $" << regularPrice << endl; + cout << "Discount amount: $" << discount << endl; + cout << "Sale price: $" << salePrice << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-24.cpp b/SourceCode/Chapter 02/Pr2-24.cpp new file mode 100755 index 0000000..40576e6 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-24.cpp @@ -0,0 +1,15 @@ +// This program extracts the rightmost digit of a number. +#include +using namespace std; + +int main() +{ + int number = 12345; + int rightMost = number % 10; + + cout << "The rightmost digit in " + << number << " is " + << rightMost << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-25.cpp b/SourceCode/Chapter 02/Pr2-25.cpp new file mode 100755 index 0000000..c61968b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-25.cpp @@ -0,0 +1,24 @@ +// This program converts seconds to minutes and seconds. +#include +using namespace std; + +int main() +{ + // The total seconds is 125. + int totalSeconds = 125; + + // Variables for minutes and seconds + int minutes, seconds; + + // Get the number of minutes. + minutes = totalSeconds / 60; + + // Get the remaining seconds. + seconds = totalSeconds % 60; + + // Display the results. + cout << totalSeconds << " is equivalent to:\n"; + cout << "Minutes: " << minutes << endl; + cout << "Seconds: " << seconds << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-26.cpp b/SourceCode/Chapter 02/Pr2-26.cpp new file mode 100755 index 0000000..b8ed337 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-26.cpp @@ -0,0 +1,17 @@ +// PROGRAM: PAYROLL.CPP +// Written by Herbert Dorfmann +// This program calculates company payroll +// Last modification: 8/20/2008 +#include +using namespace std; + +int main() +{ + double payRate; // Holds the hourly pay rate + double hours; // Holds the hours worked + int employNumber; // Holds the employee number + + // The remainder of this program is left out. + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-27.cpp b/SourceCode/Chapter 02/Pr2-27.cpp new file mode 100755 index 0000000..f919e1a --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-27.cpp @@ -0,0 +1,20 @@ +/* + PROGRAM: PAYROLL.CPP + Written by Herbert Dorfmann + This program calculates company payroll + Last modification: 8/20/2008 +*/ + +#include +using namespace std; + +int main() +{ + double payRate; // Holds the hourly pay rate + double hours; // Holds the hours worked + int employNumber; // Holds the employee number + + /* The remainder of this program is left out. */ + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-28.cpp b/SourceCode/Chapter 02/Pr2-28.cpp new file mode 100755 index 0000000..cc82f54 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-28.cpp @@ -0,0 +1,20 @@ +// This program calculates the circumference of a circle. +#include +using namespace std; + +int main() +{ + // Constants + const double PI = 3.14159; + const double DIAMETER = 10.0; + + // Variable to hold the circumference + double circumference; + + // Calculate the circumference. + circumference = PI * DIAMETER; + + // Display the circumference. + cout << "The circumference is: " << circumference << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-29.cpp b/SourceCode/Chapter 02/Pr2-29.cpp new file mode 100755 index 0000000..437750e --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-29.cpp @@ -0,0 +1,5 @@ +#include +using namespace std;int main(){double shares=220.0; +double avgPrice=14.67;cout<<"There were "< +using namespace std; + +int main() +{ + cout << "Programming is "; + cout << "great fun!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-30.cpp b/SourceCode/Chapter 02/Pr2-30.cpp new file mode 100755 index 0000000..606e061 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-30.cpp @@ -0,0 +1,13 @@ +// This example is much more readable than Program 2-29. +#include +using namespace std; + +int main() +{ + double shares = 220.0; + double avgPrice = 14.67; + + cout << "There were " << shares << " shares sold at $"; + cout << avgPrice << " per share.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-4.cpp b/SourceCode/Chapter 02/Pr2-4.cpp new file mode 100755 index 0000000..040cb65 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-4.cpp @@ -0,0 +1,13 @@ +// An unruly printing program +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers"; + cout << "during the month of June:"; + cout << "Computer games"; + cout << "Coffee"; + cout << "Aspirin"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-5.cpp b/SourceCode/Chapter 02/Pr2-5.cpp new file mode 100755 index 0000000..37b640b --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-5.cpp @@ -0,0 +1,13 @@ +// A well-adjusted printing program +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers" << endl; + cout << "during the month of June:" << endl; + cout << "Computer games" << endl; + cout << "Coffee" << endl; + cout << "Aspirin" << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-6.cpp b/SourceCode/Chapter 02/Pr2-6.cpp new file mode 100755 index 0000000..6eafa61 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-6.cpp @@ -0,0 +1,12 @@ +// Yet another well-adjusted printing program +#include +using namespace std; + +int main() +{ + cout << "The following items were top sellers\n"; + cout << "during the month of June:\n"; + cout << "Computer games\nCoffee"; + cout << "\nAspirin\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-7.cpp b/SourceCode/Chapter 02/Pr2-7.cpp new file mode 100755 index 0000000..33bd0ac --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-7.cpp @@ -0,0 +1,12 @@ +// This program has a variable. +#include +using namespace std; + +int main() +{ + int number; + + number = 5; + cout << "The value in number is " << number << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-8.cpp b/SourceCode/Chapter 02/Pr2-8.cpp new file mode 100755 index 0000000..f8c4763 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-8.cpp @@ -0,0 +1,12 @@ +// This program has a variable. +#include +using namespace std; + +int main() +{ + int number; + + number = 5; + cout << "The value in number is " << "number" << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 02/Pr2-9.cpp b/SourceCode/Chapter 02/Pr2-9.cpp new file mode 100755 index 0000000..00724d8 --- /dev/null +++ b/SourceCode/Chapter 02/Pr2-9.cpp @@ -0,0 +1,12 @@ +// This program has literals and a variable. +#include +using namespace std; + +int main() +{ + int apples; + + apples = 20; + cout << "Today we sold " << apples << " bushels of apples.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-1.cpp b/SourceCode/Chapter 03/Pr3-1.cpp new file mode 100755 index 0000000..954e022 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-1.cpp @@ -0,0 +1,20 @@ +// This program asks the user to enter the length and width of +// a rectangle. It calculates the rectangle's area and displays +// the value on the screen. +#include +using namespace std; + +int main() +{ + int length, width, area; + + cout << "This program calculates the area of a "; + cout << "rectangle.\n"; + cout << "What is the length of the rectangle? "; + cin >> length; + cout << "What is the width of the rectangle? "; + cin >> width; + area = length * width; + cout << "The area of the rectangle is " << area << ".\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-10.cpp b/SourceCode/Chapter 03/Pr3-10.cpp new file mode 100755 index 0000000..9d3f281 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-10.cpp @@ -0,0 +1,17 @@ +// This program uses a type cast expression to print a character +// from a number. +#include +using namespace std; + +int main() +{ + int number = 65; + + // Display the value of the number variable. + cout << number << endl; + + // Display the value of number converted to + // the char data type. + cout << static_cast(number) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-11.cpp b/SourceCode/Chapter 03/Pr3-11.cpp new file mode 100755 index 0000000..802a63b --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-11.cpp @@ -0,0 +1,47 @@ +// This program tracks the inventory of three widget stores +// that opened at the same time. Each store started with the +// same number of widgets in inventory. By subtracting the +// number of widgets each store has sold from its inventory, +// the current inventory can be calculated. +#include +using namespace std; + +int main() +{ + int begInv, // Begining inventory for all stores + sold, // Number of widgets sold + store1, // Store 1's inventory + store2, // Store 2's inventory + store3; // Store 3's inventory + + // Get the beginning inventory for all the stores. + cout << "One week ago, 3 new widget stores opened\n"; + cout << "at the same time with the same beginning\n"; + cout << "inventory. What was the beginning inventory? "; + cin >> begInv; + + // Set each store's inventory. + store1 = store2 = store3 = begInv; + + // Get the number of widgets sold at store 1. + cout << "How many widgets has store 1 sold? "; + cin >> sold; + store1 -= sold; // Adjust store 1's inventory. + + // Get the number of widgets sold at store 2. + cout << "How many widgets has store 2 sold? "; + cin >> sold; + store2 -= sold; // Adjust store 2's inventory. + + // Get the number of widgets sold at store 3. + cout << "How many widgets has store 3 sold? "; + cin >> sold; + store3 -= sold; // Adjust store 3's inventory. + + // Display each store's current inventory. + cout << "\nThe current inventory of each store:\n"; + cout << "Store 1: " << store1 << endl; + cout << "Store 2: " << store2 << endl; + cout << "Store 3: " << store3 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-12.cpp b/SourceCode/Chapter 03/Pr3-12.cpp new file mode 100755 index 0000000..e3ace42 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-12.cpp @@ -0,0 +1,20 @@ +// This program displays three rows of numbers. +#include +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 = 1623, + num7 = 390, num8 = 3456, num9 = 12; + + // Display the first row of numbers + cout << num1 << " " << num2 << " " << num3 << endl; + + // Display the second row of numbers + cout << num4 << " " << num5 << " " << num6 << endl; + + // Display the third row of numbers + cout << num7 << " " << num8 << " " << num9 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-13.cpp b/SourceCode/Chapter 03/Pr3-13.cpp new file mode 100755 index 0000000..73be502 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-13.cpp @@ -0,0 +1,24 @@ +// This program displays three rows of numbers. +#include +#include // Required for setw +using namespace std; + +int main() +{ + int num1 = 2897, num2 = 5, num3 = 837, + num4 = 34, num5 = 7, num6 = 1623, + num7 = 390, num8 = 3456, num9 = 12; + + // Display the first row of numbers + cout << setw(6) << num1 << setw(6) + << num2 << setw(6) << num3 << endl; + + // Display the second row of numbers + cout << setw(6) << num4 << setw(6) + << num5 << setw(6) << num6 << endl; + + // Display the third row of numbers + cout << setw(6) << num7 << setw(6) + << num8 << setw(6) << num9 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-14.cpp b/SourceCode/Chapter 03/Pr3-14.cpp new file mode 100755 index 0000000..c3eb9c0 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-14.cpp @@ -0,0 +1,18 @@ +// This program demonstrates the setw manipulator being +// used with values of various data types. +#include +#include +#include +using namespace std; + +int main() +{ + int intValue = 3928; + double doubleValue = 91.5; + string stringValue = "John J. Smith"; + + cout << "(" << setw(5) << intValue << ")" << endl; + cout << "(" << setw(8) << doubleValue << ")" << endl; + cout << "(" << setw(16) << stringValue << ")" << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-15.cpp b/SourceCode/Chapter 03/Pr3-15.cpp new file mode 100755 index 0000000..9aaaeea --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-15.cpp @@ -0,0 +1,19 @@ +// This program demonstrates how setprecision rounds a +// floating point value. +#include +#include +using namespace std; + +int main() +{ + double quotient, number1 = 132.364, number2 = 26.91; + + quotient = number1 / number2; + cout << quotient << endl; + cout << setprecision(5) << quotient << endl; + cout << setprecision(4) << quotient << endl; + cout << setprecision(3) << quotient << endl; + cout << setprecision(2) << quotient << endl; + cout << setprecision(1) << quotient << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-16.cpp b/SourceCode/Chapter 03/Pr3-16.cpp new file mode 100755 index 0000000..8129817 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-16.cpp @@ -0,0 +1,31 @@ +// This program asks for sales figures for 3 days. The total +// sales are calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + // Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + // Calculate the total sales. + total = day1 + day2 + day3; + + // Display the sales figures. + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << setprecision(5); + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-17.cpp b/SourceCode/Chapter 03/Pr3-17.cpp new file mode 100755 index 0000000..01fefd2 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-17.cpp @@ -0,0 +1,31 @@ +// This program asks for sales figures for 3 days. The total +// sales are calculated and displayed in a table. +#include +#include +using namespace std; + +int main() +{ + double day1, day2, day3, total; + + // Get the sales for each day. + cout << "Enter the sales for day 1: "; + cin >> day1; + cout << "Enter the sales for day 2: "; + cin >> day2; + cout << "Enter the sales for day 3: "; + cin >> day3; + + // Calculate the total sales. + total = day1 + day2 + day3; + + // Display the sales figures. + cout << "\nSales Figures\n"; + cout << "-------------\n"; + cout << setprecision(2) << fixed; + cout << "Day 1: " << setw(8) << day1 << endl; + cout << "Day 2: " << setw(8) << day2 << endl; + cout << "Day 3: " << setw(8) << day3 << endl; + cout << "Total: " << setw(8) << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-18.cpp b/SourceCode/Chapter 03/Pr3-18.cpp new file mode 100755 index 0000000..8bb3007 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-18.cpp @@ -0,0 +1,20 @@ +// This program illustrates a problem that can occur if +// cin is used to read character data into a string object. +#include +#include +using namespace std; + +int main() +{ + string name; + string city; + + cout << "Please enter your name: "; + cin >> name; + cout << "Enter the city you live in: "; + cin >> city; + + cout << "Hello, " << name << endl; + cout << "You live in " << city << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-19.cpp b/SourceCode/Chapter 03/Pr3-19.cpp new file mode 100755 index 0000000..5c8853a --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-19.cpp @@ -0,0 +1,20 @@ +// This program demonstrates using the getline function +// to read character data into a string object. +#include +#include +using namespace std; + +int main() +{ + string name; + string city; + + cout << "Please enter your name: "; + getline(cin, name); + cout << "Enter the city you live in: "; + getline(cin, city); + + cout << "Hello, " << name << endl; + cout << "You live in " << city << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-2.cpp b/SourceCode/Chapter 03/Pr3-2.cpp new file mode 100755 index 0000000..725c3f6 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-2.cpp @@ -0,0 +1,19 @@ +// This program asks the user to enter the length and width of +// a rectangle. It calculates the rectangle's area and displays +// the value on the screen. +#include +using namespace std; + +int main() +{ + int length, width, area; + + cout << "This program calculates the area of a "; + cout << "rectangle.\n"; + cout << "Enter the length and width of the rectangle "; + cout << "separated by a space.\n"; + cin >> length >> width; + area = length * width; + cout << "The area of the rectangle is " << area << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-20.cpp b/SourceCode/Chapter 03/Pr3-20.cpp new file mode 100755 index 0000000..d87daf0 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-20.cpp @@ -0,0 +1,13 @@ +// This program reads a single character into a char variable. +#include +using namespace std; + +int main() +{ + char ch; + + cout << "Type a character and press Enter: "; + cin >> ch; + cout << "You entered " << ch << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-21.cpp b/SourceCode/Chapter 03/Pr3-21.cpp new file mode 100755 index 0000000..840cd66 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-21.cpp @@ -0,0 +1,18 @@ +// This program demonstrates three ways +// to use cin.get() to pause a program +#include +using namespace std; + +int main() +{ + char ch; + + cout << "This program has paused. Press Enter to continue."; + cin.get(ch); + cout << "It has paused a second time. Please press Enter again."; + ch = cin.get(); + cout << "It has paused a third time. Please press Enter again."; + cin.get(); + cout << "Thank you!"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-22.cpp b/SourceCode/Chapter 03/Pr3-22.cpp new file mode 100755 index 0000000..88d00f2 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-22.cpp @@ -0,0 +1,17 @@ +// This program demonstrates a problem that occurs +// when you mix cin >> with cin.get(). +#include +using namespace std; + +int main() +{ + char ch; // Define a character variable + int number; // Define an integer variable + + cout << "Enter a number: "; + cin >> number; // Read an integer + cout << "Enter a character: "; + ch = cin.get(); // Read a character + cout << "Thank You!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-23.cpp b/SourceCode/Chapter 03/Pr3-23.cpp new file mode 100755 index 0000000..b9fce11 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-23.cpp @@ -0,0 +1,18 @@ +// This program successfully uses both +// cin >> and cin.get() for keyboard input. +#include +using namespace std; + +int main() +{ + char ch; + int number; + + cout << "Enter a number: "; + cin >> number; + cin.ignore(); // Skip the newline character + cout << "Enter a character: "; + ch = cin.get(); + cout << "Thank You!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-24.cpp b/SourceCode/Chapter 03/Pr3-24.cpp new file mode 100755 index 0000000..5bae12c --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-24.cpp @@ -0,0 +1,21 @@ +// This program asks for the lengths of the two sides of a +// right triangle. The length of the hypotenuse is then +// calculated and displayed. +#include +#include // For setprecision +#include // For the sqrt and pow functions +using namespace std; + +int main() +{ + double a, b, c; + + cout << "Enter the length of side a: "; + cin >> a; + cout << "Enter the length of side b: "; + cin >> b; + c = sqrt(pow(a, 2.0) + pow(b, 2.0)); + cout << "The length of the hypotenuse is "; + cout << setprecision(2) << c << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-25.cpp b/SourceCode/Chapter 03/Pr3-25.cpp new file mode 100755 index 0000000..45649b5 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-25.cpp @@ -0,0 +1,20 @@ +// This program demonstrates random numbers. +#include +#include // rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + // Display three random numbers. + cout << rand() << endl; + cout << rand() << endl; + cout << rand() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-26.cpp b/SourceCode/Chapter 03/Pr3-26.cpp new file mode 100755 index 0000000..97125e5 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-26.cpp @@ -0,0 +1,29 @@ +// This program simulates rolling dice. +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +int main() +{ + // Constants + const int MIN_VALUE = 1; // Minimum die value + const int MAX_VALUE = 6; // Maximum die value + + // Variables + int die1; // To hold the value of die #1 + int die2; // To hold the value of die #2 + + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + cout << "Rolling the dice...\n"; + die1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + die2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << die1 << endl; + cout << die2 << endl; + return 0; +} diff --git a/SourceCode/Chapter 03/Pr3-27.cpp b/SourceCode/Chapter 03/Pr3-27.cpp new file mode 100755 index 0000000..09209f2 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-27.cpp @@ -0,0 +1,19 @@ +// This program asks for three numbers, then +// displays the average of the numbers. +#include +using namespace std; + +int main() +{ + double num1, num2, num3, avg; + + cout << "Enter the first number: "; + cin >> num1; + cout << "Enter the second number: "; + cin >> num2; + cout << "Enter the third number: "; + cin >> num3; + avg = (num1 + num2 + num3) / 3; + cout << "The average is " << avg << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-28.cpp b/SourceCode/Chapter 03/Pr3-28.cpp new file mode 100755 index 0000000..b48623a --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-28.cpp @@ -0,0 +1,50 @@ +// This program is used by General Crates, Inc. to calculate +// the volume, cost, customer charge, and profit of a crate +// of any size. It calculates this data from user input, which +// consists of the dimensions of the crate. +#include +#include +using namespace std; + +int main() +{ + // Constants for cost and amount charged + const double COST_PER_CUBIC_FOOT = 0.23; + const double CHARGE_PER_CUBIC_FOOT = 0.5; + + // Variables + double length, // The crate's length + width, // The crate's width + height, // The crate's height + volume, // The volume of the crate + cost, // The cost to build the crate + charge, // The customer charge for the crate + profit; // The profit made on the crate + + // Set the desired output formatting for numbers. + cout << setprecision(2) << fixed << showpoint; + + // Prompt the user for the crate's length, width, and height + cout << "Enter the dimensions of the crate (in feet):\n"; + cout << "Length: "; + cin >> length; + cout << "Width: "; + cin >> width; + cout << "Height: "; + cin >> height; + + // Calculate the crate's volume, the cost to produce it, + // the charge to the customer, and the profit. + volume = length * width * height; + cost = volume * COST_PER_CUBIC_FOOT; + charge = volume * CHARGE_PER_CUBIC_FOOT; + profit = charge - cost; + + // Display the calculated data. + cout << "The volume of the crate is "; + cout << volume << " cubic feet.\n"; + cout << "Cost to build: $" << cost << endl; + cout << "Charge to customer: $" << charge << endl; + cout << "Profit: $" << profit << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-3.cpp b/SourceCode/Chapter 03/Pr3-3.cpp new file mode 100755 index 0000000..0aaa41d --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-3.cpp @@ -0,0 +1,18 @@ +// This program demonstrates how cin can read multiple values +// of different data types. +#include +using namespace std; + +int main() +{ + int whole; + double fractional; + char letter; + + cout << "Enter an integer, a double, and a character: "; + cin >> whole >> fractional >> letter; + cout << "Whole: " << whole << endl; + cout << "Fractional: " << fractional << endl; + cout << "Letter: " << letter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-4.cpp b/SourceCode/Chapter 03/Pr3-4.cpp new file mode 100755 index 0000000..61ee984 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-4.cpp @@ -0,0 +1,21 @@ +// This program asks the user to enter the numerator +// and denominator of a fraction and it displays the +// decimal value. + +#include +using namespace std; + +int main() +{ + double numerator, denominator; + + cout << "This program shows the decimal value of "; + cout << "a fraction.\n"; + cout << "Enter the numerator: "; + cin >> numerator; + cout << "Enter the denominator: "; + cin >> denominator; + cout << "The decimal value is "; + cout << (numerator / denominator) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-5.cpp b/SourceCode/Chapter 03/Pr3-5.cpp new file mode 100755 index 0000000..1c1fea9 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-5.cpp @@ -0,0 +1,19 @@ +// This program calculates the area of a circle. +// The formula for the area of a circle is Pi times +// the radius squared. Pi is 3.14159. +#include +#include // needed for pow function +using namespace std; + +int main() +{ + const double PI = 3.14159; + double area, radius; + + cout << "This program calculates the area of a circle.\n"; + cout << "What is the radius of the circle? "; + cin >> radius; + area = PI * pow(radius, 2.0); + cout << "The area is " << area << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-6.cpp b/SourceCode/Chapter 03/Pr3-6.cpp new file mode 100755 index 0000000..0843f2c --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-6.cpp @@ -0,0 +1,26 @@ +// This program calculates the average +// of three test scores. +#include +#include +using namespace std; + +int main() +{ + double test1, test2, test3; // To hold the scores + double average; // To hold the average + + // Get the three test scores. + cout << "Enter the first test score: "; + cin >> test1; + cout << "Enter the second test score: "; + cin >> test2; + cout << "Enter the third test score: "; + cin >> test3; + + // Calculate the average of the scores. + average = (test1 + test2 + test3) / 3.0; + + // Display the average. + cout << "The average score is: " << average << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-7.cpp b/SourceCode/Chapter 03/Pr3-7.cpp new file mode 100755 index 0000000..29447a4 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-7.cpp @@ -0,0 +1,21 @@ +// This program demonstrates integer overflow and underflow. +#include +using namespace std; + +int main() +{ + // testVar is initialized with the maximum value for a short. + short testVar = 32767; + + // Display testVar. + cout << testVar << endl; + + // Add 1 to testVar to make it overflow. + testVar = testVar + 1; + cout << testVar << endl; + + // Subtract 1 from testVar to make it underflow. + testVar = testVar - 1; + cout << testVar << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-8.cpp b/SourceCode/Chapter 03/Pr3-8.cpp new file mode 100755 index 0000000..521e691 --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-8.cpp @@ -0,0 +1,15 @@ +// This program can be used to see how your system handles +// floating point overflow and underflow. +#include +using namespace std; + +int main() +{ + float test; + + test = 2.0e38 * 1000; // Should overflow test. + cout << test << endl; + test = 2.0e-38 / 2.0e38; // Should underflow test. + cout << test << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 03/Pr3-9.cpp b/SourceCode/Chapter 03/Pr3-9.cpp new file mode 100755 index 0000000..bc287fb --- /dev/null +++ b/SourceCode/Chapter 03/Pr3-9.cpp @@ -0,0 +1,18 @@ +// This program uses a type cast to avoid integer division. +#include +using namespace std; + +int main() +{ + int books; // Number of books to read + int months; // Number of months spent reading + double perMonth; // Average number of books per month + + cout << "How many books do you plan to read? "; + cin >> books; + cout << "How many months will it take you to read them? "; + cin >> months; + perMonth = static_cast(books) / months; + cout << "That is " << perMonth << " books per month.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-1.cpp b/SourceCode/Chapter 04/Pr4-1.cpp new file mode 100755 index 0000000..62862ad --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-1.cpp @@ -0,0 +1,16 @@ +// This program displays the values of true and false states. +#include +using namespace std; + +int main() +{ + bool trueValue, falseValue; + int x = 5, y = 10; + + trueValue = x < y; + falseValue = y == x; + + cout << "True is " << trueValue << endl; + cout << "False is " << falseValue << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-10.cpp b/SourceCode/Chapter 04/Pr4-10.cpp new file mode 100755 index 0000000..36dc67d --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-10.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the nested if statement. +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or "; + cout << "N for No.\n"; + cout << "Are you employed? "; + cin >> employed; + cout << "Have you graduated from college "; + cout << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y') + { + if (recentGrad == 'Y') //Nested if + { + cout << "You qualify for the special "; + cout << "interest rate.\n"; + } + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-11.cpp b/SourceCode/Chapter 04/Pr4-11.cpp new file mode 100755 index 0000000..f312f4e --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-11.cpp @@ -0,0 +1,40 @@ +// This program demonstrates the nested if statement. +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or "; + cout << "N for No.\n"; + cout << "Are you employed? "; + cin >> employed; + cout << "Have you graduated from college "; + cout << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y') + { + if (recentGrad == 'Y') // Nested if + { + cout << "You qualify for the special "; + cout << "interest rate.\n"; + } + else // Not a recent grad, but employed + { + cout << "You must have graduated from "; + cout << "college in the past two\n"; + cout << "years to qualify.\n"; + } + } + else // Not employed + { + cout << "You must be employed to qualify.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-12.cpp b/SourceCode/Chapter 04/Pr4-12.cpp new file mode 100755 index 0000000..c831120 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-12.cpp @@ -0,0 +1,53 @@ +// This program uses nested if/else statements to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n"; + cout << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + { + cout << "Your grade is A.\n"; + } + else + { + if (testScore >= B_SCORE) + { + cout << "Your grade is B.\n"; + } + else + { + if (testScore >= C_SCORE) + { + cout << "Your grade is C.\n"; + } + else + { + if (testScore >= D_SCORE) + { + cout << "Your grade is D.\n"; + } + else + { + cout << "Your grade is F.\n"; + } + } + } + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-13.cpp b/SourceCode/Chapter 04/Pr4-13.cpp new file mode 100755 index 0000000..a2d282f --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-13.cpp @@ -0,0 +1,34 @@ +// This program uses an if/else if statement to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + cout << "Your grade is A.\n"; + else if (testScore >= B_SCORE) + cout << "Your grade is B.\n"; + else if (testScore >= C_SCORE) + cout << "Your grade is C.\n"; + else if (testScore >= D_SCORE) + cout << "Your grade is D.\n"; + else + cout << "Your grade is F.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-14.cpp b/SourceCode/Chapter 04/Pr4-14.cpp new file mode 100755 index 0000000..acc40db --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-14.cpp @@ -0,0 +1,36 @@ +// This program uses an if/else if statement to assign a +// letter grade (A, B, C, D, or F) to a numeric test score. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60; + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Determine the letter grade. + if (testScore >= A_SCORE) + cout << "Your grade is A.\n"; + else if (testScore >= B_SCORE) + cout << "Your grade is B.\n"; + else if (testScore >= C_SCORE) + cout << "Your grade is C.\n"; + else if (testScore >= D_SCORE) + cout << "Your grade is D.\n"; + else if (testScore >= 0) + cout << "Your grade is F.\n"; + else + cout << "Invalid test score.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-15.cpp b/SourceCode/Chapter 04/Pr4-15.cpp new file mode 100755 index 0000000..d3019b9 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-15.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the && logical operator. +#include +using namespace std; + +int main() +{ + char employed, // Currently employed, Y or N + recentGrad; // Recent graduate, Y or N + + // Is the user employed and a recent graduate? + cout << "Answer the following questions\n"; + cout << "with either Y for Yes or N for No.\n"; + + cout << "Are you employed? "; + cin >> employed; + + cout << "Have you graduated from college " + << "in the past two years? "; + cin >> recentGrad; + + // Determine the user's loan qualifications. + if (employed == 'Y' && recentGrad == 'Y') + { + cout << "You qualify for the special " + << "interest rate.\n"; + } + else + { + cout << "You must be employed and have\n" + << "graduated from college in the\n" + << "past two years to qualify.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-16.cpp b/SourceCode/Chapter 04/Pr4-16.cpp new file mode 100755 index 0000000..029ec6b --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-16.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the logical || operator. +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + double income; // Annual income + int years; // Years at the current job + + // Get the annual income + cout << "What is your annual income? "; + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + cin >> years; + + // Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-17.cpp b/SourceCode/Chapter 04/Pr4-17.cpp new file mode 100755 index 0000000..7497012 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-17.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the logical ! operator. +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + double income; // Annual income + int years; // Years at the current job + + // Get the annual income + cout << "What is your annual income? "; + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + cin >> years; + + // Determine the user's loan qualifications. + if (!(income >= MIN_INCOME || years > MIN_YEARS)) + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << "years.\n"; + } + else + cout << "You qualify.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-18.cpp b/SourceCode/Chapter 04/Pr4-18.cpp new file mode 100755 index 0000000..aa9271c --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-18.cpp @@ -0,0 +1,69 @@ +// This program displays a menu and asks the user to make a +// selection. An if/else if statement determines which item +// the user has chosen. +#include +#include +using namespace std; + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold the number of months + double charges; // To hold the monthly charges + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Display the menu and get a choice. + cout << "\t\tHealth Club Membership Menu\n\n"; + cout << "1. Standard Adult Membership\n"; + cout << "2. Child Membership\n"; + cout << "3. Senior Citizen Membership\n"; + cout << "4. Quit the Program\n\n"; + cout << "Enter your choice: "; + cin >> choice; + + // Set the numeric ouput formatting. + cout << fixed << showpoint << setprecision(2); + + // Respond to the user's menu selection. + if (choice == ADULT_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * ADULT; + cout << "The total charges are $" << charges << endl; + } + else if (choice == CHILD_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * CHILD; + cout << "The total charges are $" << charges << endl; + } + else if (choice == SENIOR_CHOICE) + { + cout << "For how many months? "; + cin >> months; + charges = months * SENIOR; + cout << "The total charges are $" << charges << endl; + } + else if (choice == QUIT_CHOICE) + { + cout << "Program ending.\n"; + } + else + { + cout << "The valid choices are 1 through 4. Run the\n"; + cout << "program again and select one of those.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-19.cpp b/SourceCode/Chapter 04/Pr4-19.cpp new file mode 100755 index 0000000..33e21b7 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-19.cpp @@ -0,0 +1,47 @@ +// This test scoring program does not accept test scores +// that are less than 0 or greater than 100. +#include +using namespace std; + +int main() +{ + // Constants for grade thresholds + const int A_SCORE = 90, + B_SCORE = 80, + C_SCORE = 70, + D_SCORE = 60, + MIN_SCORE = 0, // Minimum valid score + MAX_SCORE = 100; // Maximum valid score + + int testScore; // To hold a numeric test score + + // Get the numeric test score. + cout << "Enter your numeric test score and I will\n" + << "tell you the letter grade you earned: "; + cin >> testScore; + + // Validate the input and determine the grade. + if (testScore >= MIN_SCORE && testScore <= MAX_SCORE) + { + // Determine the letter grade. + if (testScore >= A_SCORE) + cout << "Your grade is A.\n"; + else if (testScore >= B_SCORE) + cout << "Your grade is B.\n"; + else if (testScore >= C_SCORE) + cout << "Your grade is C.\n"; + else if (testScore >= D_SCORE) + cout << "Your grade is D.\n"; + else + cout << "Your grade is F.\n"; + } + else + { + // An invalid score was entered. + cout << "That is an invalid score. Run the program\n" + << "again and enter a value in the range of\n" + << MIN_SCORE << " through " << MAX_SCORE << ".\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-2.cpp b/SourceCode/Chapter 04/Pr4-2.cpp new file mode 100755 index 0000000..470c80b --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-2.cpp @@ -0,0 +1,25 @@ +// This program averages three test scores +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 or greater + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // If the average is a high score, congratulate the user. + if (average > HIGH_SCORE) + cout << "Congratulations! That's a high score!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-20.cpp b/SourceCode/Chapter 04/Pr4-20.cpp new file mode 100755 index 0000000..3f3b13a --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-20.cpp @@ -0,0 +1,25 @@ +// This program demonstrates how characters can be +// compared with the relational operators. +#include +using namespace std; + +int main() +{ + char ch; + + // Get a character from the user. + cout << "Enter a digit or a letter: "; + ch = cin.get(); + + // Determine what the user entered. + if (ch >= '0' && ch <= '9') + cout << "You entered a digit.\n"; + else if (ch >= 'A' && ch <= 'Z') + cout << "You entered an uppercase letter.\n"; + else if (ch >= 'a' && ch <= 'z') + cout << "You entered a lowercase letter.\n"; + else + cout << "That is not a digit or a letter.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-21.cpp b/SourceCode/Chapter 04/Pr4-21.cpp new file mode 100755 index 0000000..f1d2fc5 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-21.cpp @@ -0,0 +1,34 @@ +// This program uses relational operators to compare a string +// entered by the user with valid stereo part numbers. +#include +#include +#include +using namespace std; + +int main() +{ + const double PRICE_A = 249.0, + PRICE_B = 299.0; + + string partNum; // Holds a stereo part number + + // Display available parts and get the user's selection + cout << "The stereo part numbers are:\n" + << "Boom Box : part number S-29A \n" + << "Shelf Model: part number S-29B \n" + << "Enter the part number of the stereo you\n" + << "wish to purchase: "; + cin >> partNum; + + // Set the numeric output formatting + cout << fixed << showpoint << setprecision(2); + + // Determine and display the correct price + if (partNum == "S-29A") + cout << "The price is $" << PRICE_A << endl; + else if (partNum == "S-29B") + cout << "The price is $" << PRICE_B << endl; + else + cout << partNum << " is not a valid part number.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-22.cpp b/SourceCode/Chapter 04/Pr4-22.cpp new file mode 100755 index 0000000..42d7980 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-22.cpp @@ -0,0 +1,27 @@ +// This program calculates a consultant's charges at $50 +// per hour, for a minimum of 5 hours. The ?: operator +// adjusts hours to 5 if less than 5 hours were worked. +#include +#include +using namespace std; + +int main() +{ + const double PAY_RATE = 50.0; // Hourly pay rate + const int MIN_HOURS = 5; // Minimum billable hours + double hours, // Hours worked + charges; // Total charges + + // Get the hours worked. + cout << "How many hours were worked? "; + cin >> hours; + + // Determine the hours to charge for. + hours = hours < MIN_HOURS ? MIN_HOURS : hours; + + // Calculate and display the charges. + charges = PAY_RATE * hours; + cout << fixed << showpoint << setprecision(2) + << "The charges are $" << charges << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-23.cpp b/SourceCode/Chapter 04/Pr4-23.cpp new file mode 100755 index 0000000..b380437 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-23.cpp @@ -0,0 +1,23 @@ +// The switch statement in this program tells the user something +// he or she already knows: what they just entered! +#include +using namespace std; + +int main() +{ + char choice; + + cout << "Enter A, B, or C: "; + cin >> choice; + switch (choice) + { + case 'A': cout << "You entered A.\n"; + break; + case 'B': cout << "You entered B.\n"; + break; + case 'C': cout << "You entered C.\n"; + break; + default: cout << "You did not enter A, B, or C!\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-24.cpp b/SourceCode/Chapter 04/Pr4-24.cpp new file mode 100755 index 0000000..8150e8a --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-24.cpp @@ -0,0 +1,22 @@ +// The switch statement in this program tells the user something +// he or she already knows: what they just entered! +#include +using namespace std; + +int main() +{ + char choice; + + cout << "Enter A, B, or C: "; + cin >> choice; + // The following switch is + // missing its break statements! + switch (choice) + { + case 'A': cout << "You entered A.\n"; + case 'B': cout << "You entered B.\n"; + case 'C': cout << "You entered C.\n"; + default: cout << "You did not enter A, B, or C!\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-25.cpp b/SourceCode/Chapter 04/Pr4-25.cpp new file mode 100755 index 0000000..5c8d5ea --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-25.cpp @@ -0,0 +1,27 @@ +// This program is carefully constructed to use the "fallthrough" +// feature of the switch statement. +#include +using namespace std; + +int main() +{ + int modelNum; // Model number + + // Get a model number from the user. + cout << "Our TVs come in three models:\n"; + cout << "The 100, 200, and 300. Which do you want? "; + cin >> modelNum; + + // Display the model's features. + cout << "That model has the following features:\n"; + switch (modelNum) + { + case 300: cout << "\tPicture-in-a-picture.\n"; + case 200: cout << "\tStereo sound.\n"; + case 100: cout << "\tRemote control.\n"; + break; + default: cout << "You can only choose the 100,"; + cout << "200, or 300.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-26.cpp b/SourceCode/Chapter 04/Pr4-26.cpp new file mode 100755 index 0000000..ee15e63 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-26.cpp @@ -0,0 +1,31 @@ +// The switch statement in this program uses the "fall through" +// feature to catch both uppercase and lowercase letters entered +// by the user. +#include +using namespace std; + +int main() +{ + char feedGrade; + + // Get the desired grade of feed. + cout << "Our pet food is available in three grades:\n"; + cout << "A, B, and C. Which do you want pricing for? "; + cin >> feedGrade; + + // Display the price. + switch(feedGrade) + { + case 'a': + case 'A': cout << "30 cents per pound.\n"; + break; + case 'b': + case 'B': cout << "20 cents per pound.\n"; + break; + case 'c': + case 'C': cout << "15 cents per pound.\n"; + break; + default: cout << "That is an invalid choice.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-27.cpp b/SourceCode/Chapter 04/Pr4-27.cpp new file mode 100755 index 0000000..edcc0d9 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-27.cpp @@ -0,0 +1,70 @@ +// This program uses a switch statement to determine +// the item selected from a menu. +#include +#include +using namespace std; + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold the number of months + double charges; // To hold the monthly charges + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Display the menu and get a choice. + cout << "\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Set the numeric ouput formatting. + cout << fixed << showpoint << setprecision(2); + + // Respond to the user's menu selection. + switch (choice) + { + case ADULT_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * ADULT; + cout << "The total charges are $" << charges << endl; + break; + + case CHILD_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * CHILD; + cout << "The total charges are $" << charges << endl; + break; + + case SENIOR_CHOICE: + cout << "For how many months? "; + cin >> months; + charges = months * SENIOR; + cout << "The total charges are $" << charges << endl; + break; + + case QUIT_CHOICE: + cout << "Program ending.\n"; + break; + + default: + cout << "The valid choices are 1 through 4. Run the\n" + << "program again and select one of those.\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-28.cpp b/SourceCode/Chapter 04/Pr4-28.cpp new file mode 100755 index 0000000..3edc77d --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-28.cpp @@ -0,0 +1,33 @@ +// This program demonstrates late variable definition +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Get the annual income. + cout << "What is your annual income? "; + double income; // Variable definition + cin >> income; + + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + int years; // Variable definition + cin >> years; + + // Determine the user's loan qualifications. + if (income >= MIN_INCOME || years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must earn at least $" + << MIN_INCOME << " or have been " + << "employed more than " << MIN_YEARS + << " years.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-29.cpp b/SourceCode/Chapter 04/Pr4-29.cpp new file mode 100755 index 0000000..5289690 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-29.cpp @@ -0,0 +1,39 @@ +// This program demonstrates a variable defined in an inner block. +#include +using namespace std; + +int main() +{ + // Constants for minimum income and years + const double MIN_INCOME = 35000.0; + const int MIN_YEARS = 5; + + // Get the annual income. + cout << "What is your annual income? "; + double income; // Variable definition + cin >> income; + + if (income >= MIN_INCOME) + { + // Get the number of years at the current job. + cout << "How many years have you worked at " + << "your current job? "; + int years; // Variable definition + cin >> years; + + if (years > MIN_YEARS) + cout << "You qualify.\n"; + else + { + cout << "You must have been employed for\n" + << "more than " << MIN_YEARS + << " years to qualify.\n"; + } + } + else + { + cout << "You must earn at least $" << MIN_INCOME + << " to qualify.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-3.cpp b/SourceCode/Chapter 04/Pr4-3.cpp new file mode 100755 index 0000000..e835d6a --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-3.cpp @@ -0,0 +1,14 @@ +// This program demonstrates how a misplaced semicolon +// prematurely terminates an if statement. +#include +using namespace std; + +int main() +{ + int x = 0, y = 10; + + cout << "x is " << x << " and y is " << y << endl; + if (x > y); // Error! Misplaced semicolon + cout << "x is greater than y\n"; //This is always executed. + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-30.cpp b/SourceCode/Chapter 04/Pr4-30.cpp new file mode 100755 index 0000000..a20392f --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-30.cpp @@ -0,0 +1,22 @@ +// This program uses two variables with the name number. +#include +using namespace std; + +int main() +{ + // Define a variable named number. + int number; + + cout << "Enter a number greater than 0: "; + cin >> number; + if (number > 0) + { + int number; // Another variable named number. + cout << "Now enter another number: "; + cin >> number; + cout << "The second number you entered was " + << number << endl; + } + cout << "Your first number was " << number << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-4.cpp b/SourceCode/Chapter 04/Pr4-4.cpp new file mode 100755 index 0000000..07001e9 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-4.cpp @@ -0,0 +1,18 @@ +// This program demonstrates how floating-point +// round-off errors can make equality operations unreliable. +#include +using namespace std; + +int main() +{ + double a = 1.5; // a is 1.5. + double b = 1.5; // b is 1.5. + + a += 0.0000000000000001; // Add a little to a. + if (a == b) + cout << "Both a and b are the same.\n"; + else + cout << "a and b are not the same.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-5.cpp b/SourceCode/Chapter 04/Pr4-5.cpp new file mode 100755 index 0000000..19f250d --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-5.cpp @@ -0,0 +1,26 @@ +// This program averages 3 test scores. The if statement +// uses the = operator, but the == operator was intended. +#include +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // Our intention is to congratulate the user + // for having a perfect score. But, this doesn't work. + if (average = 100) // WRONG! This is an assignment! + cout << "Congratulations! That's a perfect score!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-6.cpp b/SourceCode/Chapter 04/Pr4-6.cpp new file mode 100755 index 0000000..5fd279b --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-6.cpp @@ -0,0 +1,31 @@ +// This program averages 3 test scores. +// It demonstrates an if statement executing +// a block of statements. +#include +#include +using namespace std; + +int main() +{ + const int HIGH_SCORE = 95; // A high score is 95 or greater + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // If the average is high, congratulate the user. + if (average > HIGH_SCORE) + { + cout << "Congratulations!\n"; + cout << "That's a high score.\n"; + cout << "You deserve a pat on the back!\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-7.cpp b/SourceCode/Chapter 04/Pr4-7.cpp new file mode 100755 index 0000000..6ba37a6 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-7.cpp @@ -0,0 +1,27 @@ +// This program averages 3 test scores. The braces +// were inadvertently left out of the if statement. +#include +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // To hold three test scores + double average; // TO hold the average score + + // Get the three test scores. + cout << "Enter 3 test scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average score. + average = (score1 + score2 + score3) / 3.0; + cout << fixed << showpoint << setprecision(1); + cout << "Your average is " << average << endl; + + // ERROR! This if statement is missing its braces! + if (average > 95) + cout << "Congratulations!\n"; + cout << "That's a high score.\n"; + cout << "You deserve a pat on the back!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-8.cpp b/SourceCode/Chapter 04/Pr4-8.cpp new file mode 100755 index 0000000..e36dda3 --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-8.cpp @@ -0,0 +1,19 @@ +// This program uses the modulus operator to determine +// if a number is odd or even. If the number is evenly divisible +// by 2, it is an even number. A remainder indicates it is odd. +#include +using namespace std; + +int main() +{ + int number; + + cout << "Enter an integer and I will tell you if it\n"; + cout << "is odd or even. "; + cin >> number; + if (number % 2 == 0) + cout << number << " is even.\n"; + else + cout << number << " is odd.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 04/Pr4-9.cpp b/SourceCode/Chapter 04/Pr4-9.cpp new file mode 100755 index 0000000..048d9ce --- /dev/null +++ b/SourceCode/Chapter 04/Pr4-9.cpp @@ -0,0 +1,35 @@ +// This program asks the user for two numbers, num1 and num2. +// num1 is divided by num2 and the result is displayed. +// Before the division operation, however, num2 is tested +// for the value 0. If it contains 0, the division does not +// take place. +#include +using namespace std; + +int main() +{ + double num1, num2, quotient; + + // Get the first number. + cout << "Enter a number: "; + cin >> num1; + + // Get the second number. + cout << "Enter another number: "; + cin >> num2; + + // If num2 is not zero, perform the division. + if (num2 == 0) + { + cout << "Division by zero is not possible.\n"; + cout << "Please run the program again and enter\n"; + cout << "a number other than zero.\n"; + } + else + { + quotient = num1 / num2; + cout << "The quotient of " << num1 << " divided by "; + cout<< num2 << " is " << quotient << ".\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Friends.txt b/SourceCode/Chapter 05/Friends.txt new file mode 100755 index 0000000..fbd56b8 --- /dev/null +++ b/SourceCode/Chapter 05/Friends.txt @@ -0,0 +1,3 @@ +Joe +Chris +Geri diff --git a/SourceCode/Chapter 05/ListOfNumbers.txt b/SourceCode/Chapter 05/ListOfNumbers.txt new file mode 100755 index 0000000..c910440 --- /dev/null +++ b/SourceCode/Chapter 05/ListOfNumbers.txt @@ -0,0 +1,7 @@ +100 +200 +300 +400 +500 +600 +700 \ No newline at end of file diff --git a/SourceCode/Chapter 05/Numbers.txt b/SourceCode/Chapter 05/Numbers.txt new file mode 100755 index 0000000..e8d05cd --- /dev/null +++ b/SourceCode/Chapter 05/Numbers.txt @@ -0,0 +1,3 @@ +100 +200 +300 diff --git a/SourceCode/Chapter 05/NumericData.txt b/SourceCode/Chapter 05/NumericData.txt new file mode 100755 index 0000000..17b1d2b --- /dev/null +++ b/SourceCode/Chapter 05/NumericData.txt @@ -0,0 +1,3 @@ +10 +20 +30 \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-1.cpp b/SourceCode/Chapter 05/Pr5-1.cpp new file mode 100755 index 0000000..6430715 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-1.cpp @@ -0,0 +1,32 @@ +// This program demonstrates the ++ and -- operators. +#include +using namespace std; + +int main() +{ + int num = 4; // num starts out with 4. + + // Display the value in num. + cout << "The variable num is " << num << endl; + cout << "I will now increment num.\n\n"; + + // Use postfix ++ to increment num. + num++; + cout << "Now the variable num is " << num << endl; + cout << "I will increment num again.\n\n"; + + // Use prefix ++ to increment num. + ++num; + cout << "Now the variable num is " << num << endl; + cout << "I will now decrement num.\n\n"; + + // Use postfix -- to decrement num. + num--; + cout << "Now the variable num is " << num << endl; + cout << "I will decrement num again.\n\n"; + + // Use prefix -- to increment num. + --num; + cout << "Now the variable num is " << num << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-10.cpp b/SourceCode/Chapter 05/Pr5-10.cpp new file mode 100755 index 0000000..b5d75ee --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-10.cpp @@ -0,0 +1,26 @@ +// This program demonstrates a user controlled for loop. +#include +using namespace std; + +int main() +{ + int minNumber, // Starting number to square + maxNumber; // Maximum number to square + + // Get the minimum and maximum values to display. + cout << "I will display a table of numbers and " + << "their squares.\n" + << "Enter the starting number: "; + cin >> minNumber; + cout << "Enter the ending number: "; + cin >> maxNumber; + + // Display the table. + cout << "Number Number Squared\n" + << "-------------------------\n"; + + for (int num = minNumber; num <= maxNumber; num++) + cout << num << "\t\t" << (num * num) << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-11.cpp b/SourceCode/Chapter 05/Pr5-11.cpp new file mode 100755 index 0000000..63d030b --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-11.cpp @@ -0,0 +1,39 @@ +// This program converts the speeds 60 kph through +// 130 kph (in 10 kph increments) to mph. +#include +#include +using namespace std; + +int main() +{ + // Constants for the speeds + const int START_KPH = 60, // Starting speed + END_KPH = 130, // Ending speed + INCREMENT = 10; // Speed increment + + // Constant for the conversion factor + const double CONVERSION_FACTOR = 0.6214; + + // Variables + int kph; // To hold speeds in kph + double mph; // To hold speeds in mph + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display the table headings. + cout << "KPH\tMPH\n"; + cout << "---------------\n"; + + // Display the speeds. + for (kph = START_KPH; kph <= END_KPH; kph += INCREMENT) + { + // Calculate mph + mph = kph * CONVERSION_FACTOR; + + // Display the speeds in kph and mph. + cout << kph << "\t" << mph << endl; + + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-12.cpp b/SourceCode/Chapter 05/Pr5-12.cpp new file mode 100755 index 0000000..9a493f5 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-12.cpp @@ -0,0 +1,29 @@ +// This program takes daily sales figures over a period of time +// and calculates their total. +#include +#include +using namespace std; + +int main() +{ + int days; // Number of days + double total = 0.0; // Accumulator, initialized with 0 + + // Get the number of days. + cout << "For how many days do you have sales figures? "; + cin >> days; + + // Get the sales for each day and accumulate a total. + for (int count = 1; count <= days; count++) + { + double sales; + cout << "Enter the sales for day " << count << ": "; + cin >> sales; + total += sales; // Accumulate the running total. + } + + // Display the total sales. + cout << fixed << showpoint << setprecision(2); + cout << "The total sales are $" << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-13.cpp b/SourceCode/Chapter 05/Pr5-13.cpp new file mode 100755 index 0000000..8f5c873 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-13.cpp @@ -0,0 +1,27 @@ +// This program calculates the total number of points a +// soccer team has earned over a series of games. The user +// enters a series of point values, then -1 when finished. +#include +using namespace std; + +int main() +{ + int game = 1, // Game counter + points, // To hold a number of points + total = 0; // Accumulator + + cout << "Enter the number of points your team has earned\n"; + cout << "so far in the season, then enter -1 when finished.\n\n"; + cout << "Enter the points for game " << game << ": "; + cin >> points; + + while (points != -1) + { + total += points; + game++; + cout << "Enter the points for game " << game << ": "; + cin >> points; + } + cout << "\nThe total points are " << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-14.cpp b/SourceCode/Chapter 05/Pr5-14.cpp new file mode 100755 index 0000000..d27d88f --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-14.cpp @@ -0,0 +1,43 @@ +// This program averages test scores. It asks the user for the +// number of students and the number of test scores per student. +#include +#include +using namespace std; + +int main() +{ + int numStudents, // Number of students + numTests; // Number of tests per student + double total, // Accumulator for total scores + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the number of students. + cout << "This program averages test scores.\n"; + cout << "For how many students do you have scores? "; + cin >> numStudents; + + // Get the number of test scores per student. + cout << "How many test scores does each student have? "; + cin >> numTests; + + // Determine each student's average score. + for (int student = 1; student <= numStudents; student++) + { + total = 0; // Initialize the accumulator. + for (int test = 1; test <= numTests; test++) + { + double score; + cout << "Enter score " << test << " for "; + cout << "student " << student << ": "; + cin >> score; + total += score; + } + average = total / numTests; + cout << "The average score for student " << student; + cout << " is " << average << ".\n\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-15.cpp b/SourceCode/Chapter 05/Pr5-15.cpp new file mode 100755 index 0000000..4af305c --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-15.cpp @@ -0,0 +1,23 @@ +// This program writes data to a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile.txt"); + + cout << "Now writing data to the file.\n"; + + // Write four names to the file. + outputFile << "Bach\n"; + outputFile << "Beethoven\n"; + outputFile << "Mozart\n"; + outputFile << "Schubert\n"; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-16.cpp b/SourceCode/Chapter 05/Pr5-16.cpp new file mode 100755 index 0000000..a047327 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-16.cpp @@ -0,0 +1,23 @@ +// This program writes data to a single line in a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + outputFile.open("demofile.txt"); + + cout << "Now writing data to the file.\n"; + + // Write four names to the file. + outputFile << "Bach"; + outputFile << "Beethoven"; + outputFile << "Mozart"; + outputFile << "Schubert"; + + // Close the file + outputFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-17.cpp b/SourceCode/Chapter 05/Pr5-17.cpp new file mode 100755 index 0000000..2e3ac79 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-17.cpp @@ -0,0 +1,32 @@ +// This program writes user input to a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + int number1, number2, number3; + + // Open an output file. + outputFile.open("Numbers.txt"); + + // Get three numbers from the user. + cout << "Enter a number: "; + cin >> number1; + cout << "Enter another number: "; + cin >> number2; + cout << "One more time. Enter a number: "; + cin >> number3; + + // Write the numbers to the file. + outputFile << number1 << endl; + outputFile << number2 << endl; + outputFile << number3 << endl; + cout << "The numbers were saved to a file.\n"; + + // Close the file. + outputFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-18.cpp b/SourceCode/Chapter 05/Pr5-18.cpp new file mode 100755 index 0000000..da20e05 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-18.cpp @@ -0,0 +1,33 @@ +// This program writes user input to a file. +#include +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; + string name1, name2, name3; + + // Open an output file. + outputFile.open("Friends.txt"); + + // Get the names of three friends. + cout << "Enter the names of three friends.\n"; + cout << "Friend #1: "; + cin >> name1; + cout << "Friend #2: "; + cin >> name2; + cout << "Friend #3: "; + cin >> name3; + + // Write the names to the file. + outputFile << name1 << endl; + outputFile << name2 << endl; + outputFile << name3 << endl; + cout << "The names were saved to a file.\n"; + + // Close the file + outputFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-19.cpp b/SourceCode/Chapter 05/Pr5-19.cpp new file mode 100755 index 0000000..8786eb5 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-19.cpp @@ -0,0 +1,26 @@ +// This program reads data from a file. +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string name; + + inputFile.open("Friends.txt"); + cout << "Reading data from the file.\n"; + + inputFile >> name; // Read name 1 from the file + cout << name << endl; // Display name 1 + + inputFile >> name; // Read name 2 from the file + cout << name << endl; // Display name 2 + + inputFile >> name; // Read name 3 from the file + cout << name << endl; // Display name 3 + + inputFile.close(); // Close the file + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-2.cpp b/SourceCode/Chapter 05/Pr5-2.cpp new file mode 100755 index 0000000..d69d6c1 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-2.cpp @@ -0,0 +1,22 @@ +// This program demonstrates the prefix and postfix +// modes of the increment and decrement operators. +#include +using namespace std; + +int main() +{ + int num = 4; + + cout << num << endl; // Displays 4 + cout << num++ << endl; // Displays 4, then adds 1 to num + cout << num << endl; // Displays 5 + cout << ++num << endl; // Adds 1 to num, then displays 6 + cout << endl; // Displays a blank line + + cout << num << endl; // Displays 6 + cout << num-- << endl; // Displays 6, then subtracts 1 from num + cout << num << endl; // Displays 5 + cout << --num << endl; // Subtracts 1 from num, then displays 4 + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-20.cpp b/SourceCode/Chapter 05/Pr5-20.cpp new file mode 100755 index 0000000..c9d5fc8 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-20.cpp @@ -0,0 +1,33 @@ +// This program reads numbers from a file. +#include +#include +using namespace std; + +int main() +{ + ifstream inFile; + int value1, value2, value3, sum; + + // Open the file. + inFile.open("NumericData.txt"); + + // Read the three numbers from the file. + inFile >> value1; + inFile >> value2; + inFile >> value3; + + // Close the file. + inFile.close(); + + // Calculate the sum of the numbers. + sum = value1 + value2 + value3; + + // Display the three numbers. + cout << "Here are the numbers:\n" + << value1 << " " << value2 + << " " << value3 << endl; + + // Display the sum of the numbers. + cout << "Their sum is: " << sum << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-21.cpp b/SourceCode/Chapter 05/Pr5-21.cpp new file mode 100755 index 0000000..59a08a1 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-21.cpp @@ -0,0 +1,36 @@ +// This program writes user input to a file. +#include +#include +using namespace std; + +int main() +{ + ofstream outputFile; // File stream object + int numberOfDays; // Number of days of sales + double sales; // Sales amount for a day + + // Get the number of days. + cout << "For how many days do you have sales? "; + cin >> numberOfDays; + + // Open a file named Sales.txt. + outputFile.open("Sales.txt"); + + // Get the sales for each day and write it + // to the file. + for (int count = 1; count <= numberOfDays; count++) + { + // Get the sales for a day. + cout << "Enter the sales for day " + << count << ": "; + cin >> sales; + + // Write the sales to the file. + outputFile << sales << endl; + } + + // Close the file. + outputFile.close(); + cout << "Data written to Sales.txt\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-22.cpp b/SourceCode/Chapter 05/Pr5-22.cpp new file mode 100755 index 0000000..df80593 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-22.cpp @@ -0,0 +1,24 @@ +// This program reads data from a file. +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open the file. + inputFile.open("ListOfNumbers.txt"); + + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-23.cpp b/SourceCode/Chapter 05/Pr5-23.cpp new file mode 100755 index 0000000..f34c7dc --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-23.cpp @@ -0,0 +1,33 @@ +// This program tests for file open errors. +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + int number; + + // Open the file. + inputFile.open("BadListOfNumbers.txt"); + + // If the file successfully opened, process it. + if (inputFile) + { + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + } + else + { + // Display an error message. + cout << "Error opening the file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-24.cpp b/SourceCode/Chapter 05/Pr5-24.cpp new file mode 100755 index 0000000..24470bf --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-24.cpp @@ -0,0 +1,39 @@ +// This program lets the user enter a filename. +#include +#include +#include +using namespace std; + +int main() +{ + ifstream inputFile; + string filename; + int number; + + // Get the filename from the user. + cout << "Enter the filename: "; + cin >> filename; + + // Open the file. + inputFile.open(filename); + + // If the file successfully opened, process it. + if (inputFile) + { + // Read the numbers from the file and + // display them. + while (inputFile >> number) + { + cout << number << endl; + } + + // Close the file. + inputFile.close(); + } + else + { + // Display an error message. + cout << "Error opening the file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-25.cpp b/SourceCode/Chapter 05/Pr5-25.cpp new file mode 100755 index 0000000..f91ef0b --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-25.cpp @@ -0,0 +1,27 @@ +// This program raises the user's number to the powers +// of 0 through 10. +#include +#include +using namespace std; + +int main() +{ + int value; + char choice; + + cout << "Enter a number: "; + cin >> value; + cout << "This program will raise " << value; + cout << " to the powers of 0 through 10.\n"; + for (int count = 0; count <= 10; count++) + { + cout << value << " raised to the power of "; + cout << count << " is " << pow(value, count); + cout << "\nEnter Q to quit or any other key "; + cout << "to continue. "; + cin >> choice; + if (choice == 'Q' || choice == 'q') + break; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-26.cpp b/SourceCode/Chapter 05/Pr5-26.cpp new file mode 100755 index 0000000..19a5ee9 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-26.cpp @@ -0,0 +1,39 @@ +// This program calculates the charges for DVD rentals. +// Every third DVD is free. +#include +#include +using namespace std; + +int main() +{ + int dvdCount = 1; // DVD counter + int numDVDs; // Number of DVDs rented + double total = 0.0; // Accumulator + char current; // Current release, Y or N + + // Get the number of DVDs. + cout << "How many DVDs are being rented? "; + cin >> numDVDs; + + // Determine the charges. + do + { + if ((dvdCount % 3) == 0) + { + cout << "DVD #" << dvdCount << " is free!\n"; + continue; // Immediately start the next iteration + } + cout << "Is DVD #" << dvdCount; + cout << " a current release? (Y/N) "; + cin >> current; + if (current == 'Y' || current == 'y') + total += 3.50; + else + total += 2.50; + } while (dvdCount++ < numDVDs); + + // Display the total. + cout << fixed << showpoint << setprecision(2); + cout << "The total is $" << total << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-3.cpp b/SourceCode/Chapter 05/Pr5-3.cpp new file mode 100755 index 0000000..c16e526 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-3.cpp @@ -0,0 +1,16 @@ +// This program demonstrates a simple while loop. +#include +using namespace std; + +int main() +{ + int number = 0; + + while (number < 5) + { + cout << "Hello\n"; + number++; + } + cout << "That's all!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-4.cpp b/SourceCode/Chapter 05/Pr5-4.cpp new file mode 100755 index 0000000..b2acfcf --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-4.cpp @@ -0,0 +1,32 @@ +// This program assists a technician in the process +// of checking a substance's temperature. +#include +using namespace std; + +int main() +{ + const double MAX_TEMP = 102.5; // Maximum temperature + double temperature; // To hold the temperature + + // Get the current temperature. + cout << "Enter the substance's Celsius temperature: "; + cin >> temperature; + + // As long as necessary, instruct the technician + // to adjust the thermostat. + while (temperature > MAX_TEMP) + { + cout << "The temperature is too high. Turn the\n"; + cout << "thermostat down and wait 5 minutes.\n"; + cout << "Then take the Celsius temperature again\n"; + cout << "and enter it here: "; + cin >> temperature; + } + + // Remind the technician to check the temperature + // again in 15 minutes. + cout << "The temperature is acceptable.\n"; + cout << "Chek it again in 15 minutes.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-5.cpp b/SourceCode/Chapter 05/Pr5-5.cpp new file mode 100755 index 0000000..b572311 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-5.cpp @@ -0,0 +1,58 @@ +// This program calculates the number of soccer teams +// that a youth league may create from the number of +// available players. Input validation is demonstrated +// with while loops. +#include +using namespace std; + +int main() +{ + // Constants for minimum and maximum players + const int MIN_PLAYERS = 9, + MAX_PLAYERS = 15; + + // Variables + int players, // Number of available players + teamPlayers, // Number of desired players per team + numTeams, // Number of teams + leftOver; // Number of players left over + + // Get the number of players per team. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + + // Validate the input. + while (teamPlayers < MIN_PLAYERS || teamPlayers > MAX_PLAYERS) + { + // Explain the error. + cout << "You should have at least " << MIN_PLAYERS + << " but no more than " << MAX_PLAYERS << " per team.\n"; + + // Get the input again. + cout << "How many players do you wish per team? "; + cin >> teamPlayers; + } + + // Get the number of players available. + cout << "How many players are available? "; + cin >> players; + + // Validate the input. + while (players <= 0) + { + // Get the input again. + cout << "Please enter 0 or greater: "; + cin >> players; + } + + // Calculate the number of teams. + numTeams = players / teamPlayers; + + // Calculate the number of leftover players. + leftOver = players % teamPlayers; + + // Display the results. + cout << "There will be " << numTeams << " teams with " + << leftOver << " players left over.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-6.cpp b/SourceCode/Chapter 05/Pr5-6.cpp new file mode 100755 index 0000000..d2e7c30 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-6.cpp @@ -0,0 +1,21 @@ +// This program displays a list of numbers and +// their squares. +#include +using namespace std; + +int main() +{ + const int MIN_NUMBER = 1, // Starting number to square + MAX_NUMBER = 10; // Maximum number to square + + int num = MIN_NUMBER; // Counter + + cout << "Number Number Squared\n"; + cout << "-------------------------\n"; + while (num <= MAX_NUMBER) + { + cout << num << "\t\t" << (num * num) << endl; + num++; //Increment the counter. + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-7.cpp b/SourceCode/Chapter 05/Pr5-7.cpp new file mode 100755 index 0000000..e0a8aeb --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-7.cpp @@ -0,0 +1,27 @@ +// This program averages 3 test scores. It repeats as +// many times as the user wishes. +#include +using namespace std; + +int main() +{ + int score1, score2, score3; // Three scores + double average; // Average score + char again; // To hold Y or N input + + do + { + // Get three scores. + cout << "Enter 3 scores and I will average them: "; + cin >> score1 >> score2 >> score3; + + // Calculate and display the average. + average = (score1 + score2 + score3) / 3.0; + cout << "The average is " << average << ".\n"; + + // Does the user want to average another set? + cout << "Do you want to average another set? (Y/N) "; + cin >> again; + } while (again == 'Y' || again == 'y'); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-8.cpp b/SourceCode/Chapter 05/Pr5-8.cpp new file mode 100755 index 0000000..8636ac3 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-8.cpp @@ -0,0 +1,73 @@ +// This program displays a menu and asks the user to make a +// selection. A do-while loop repeats the program until the +// user selects item 4 from the menu. +#include +#include +using namespace std; + +int main() +{ + // Constants for menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + CHILD = 20.0, + SENIOR = 30.0; + + // Variables + int choice; // Menu choice + int months; // Number of months + double charges; // Monthly charges + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu. + cout << "\n\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the menu selection. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + // Validate and process the user's choice. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months? "; + cin >> months; + + // Respond to the user's menu selection. + switch (choice) + { + case ADULT_CHOICE: + charges = months * ADULT; + break; + case CHILD_CHOICE: + charges = months * CHILD; + break; + case SENIOR_CHOICE: + charges = months * SENIOR; + } + + // Display the monthly charges. + cout << "The total charges are $" + << charges << endl; + } + } while (choice != QUIT_CHOICE); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Pr5-9.cpp b/SourceCode/Chapter 05/Pr5-9.cpp new file mode 100755 index 0000000..e10aae0 --- /dev/null +++ b/SourceCode/Chapter 05/Pr5-9.cpp @@ -0,0 +1,19 @@ +// This program displays the numbers 1 through 10 and +// their squares. +#include +using namespace std; + +int main() +{ + const int MIN_NUMBER = 1, // Starting value + MAX_NUMBER = 10; // Ending value + int num; + + cout << "Number Number Squared\n"; + cout << "-------------------------\n"; + + for (num = MIN_NUMBER; num <= MAX_NUMBER; num++) + cout << num << "\t\t" << (num * num) << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 05/Sales.txt b/SourceCode/Chapter 05/Sales.txt new file mode 100755 index 0000000..0742e38 --- /dev/null +++ b/SourceCode/Chapter 05/Sales.txt @@ -0,0 +1,5 @@ +1000 +2000 +3000 +4000 +5000 diff --git a/SourceCode/Chapter 06/Pr6-1.cpp b/SourceCode/Chapter 06/Pr6-1.cpp new file mode 100755 index 0000000..2072fee --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-1.cpp @@ -0,0 +1,25 @@ +// This program has two functions: main and displayMessage +#include +using namespace std; + +//***************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//***************************************** + +void displayMessage() +{ + cout << "Hello from the function displayMessage.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "Hello from main.\n"; + displayMessage(); + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-10.cpp b/SourceCode/Chapter 06/Pr6-10.cpp new file mode 100755 index 0000000..d9b5adf --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-10.cpp @@ -0,0 +1,91 @@ +// This is a menu-driven program that makes a function call +// for each selection the user makes. +#include +#include +using namespace std; + +// Function prototypes +void showMenu(); +void showFees(double, int); + +int main() +{ + int choice; // To hold a menu choice + int months; // To hold a number of months + + // Constants for the menu choices + const int ADULT_CHOICE = 1, + CHILD_CHOICE = 2, + SENIOR_CHOICE = 3, + QUIT_CHOICE = 4; + + // Constants for membership rates + const double ADULT = 40.0, + SENIOR = 30.0, + CHILD = 20.0; + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu and get the user's choice. + showMenu(); + cin >> choice; + + // Validate the menu selection. + while (choice < ADULT_CHOICE || choice > QUIT_CHOICE) + { + cout << "Please enter a valid menu choice: "; + cin >> choice; + } + + // If the user does not want to quit, proceed. + if (choice != QUIT_CHOICE) + { + // Get the number of months. + cout << "For how many months? "; + cin >> months; + + // Display the membership fees. + switch (choice) + { + case ADULT_CHOICE: + showFees(ADULT, months); + break; + case CHILD_CHOICE: + showFees(CHILD, months); + break; + case SENIOR_CHOICE: + showFees(SENIOR, months); + } + } + } while (choice != QUIT_CHOICE); + return 0; +} + +//***************************************************************** +// Definition of function showMenu which displays the menu. * +//***************************************************************** + +void showMenu() +{ + cout << "\n\t\tHealth Club Membership Menu\n\n" + << "1. Standard Adult Membership\n" + << "2. Child Membership\n" + << "3. Senior Citizen Membership\n" + << "4. Quit the Program\n\n" + << "Enter your choice: "; +} + +//***************************************************************** +// Definition of function showFees. The memberRate parameter * +// the monthly membership rate and the months parameter holds the * +// number of months. The function displays the total charges. * +//***************************************************************** + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-11.cpp b/SourceCode/Chapter 06/Pr6-11.cpp new file mode 100755 index 0000000..3f3a19f --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-11.cpp @@ -0,0 +1,35 @@ +// This program uses a function to perform division. If division +// by zero is detected, the function returns. +#include +using namespace std; + +// Function prototype. +void divide(double, double); + +int main() +{ + double num1, num2; + + cout << "Enter two numbers and I will divide the first\n"; + cout << "number by the second number: "; + cin >> num1 >> num2; + divide(num1, num2); + return 0; +} + +//*************************************************************** +// Definition of function divide. * +// Uses two parameters: arg1 and arg2. The function divides arg1* +// by arg2 and shows the result. If arg2 is zero, however, the * +// function returns. * +//*************************************************************** + +void divide(double arg1, double arg2) +{ + if (arg2 == 0.0) + { + cout << "Sorry, I cannot divide by zero.\n"; + return; + } + cout << "The quotient is " << (arg1 / arg2) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-12.cpp b/SourceCode/Chapter 06/Pr6-12.cpp new file mode 100755 index 0000000..ed6efa4 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-12.cpp @@ -0,0 +1,33 @@ +// This program uses a function that returns a value. +#include +using namespace std; + +// Function prototype +int sum(int, int); + +int main() +{ + int value1 = 20, // The first value + value2 = 40, // The second value + total; // To hold the total + + // Call the sum function, passing the contents of + // value1 and value2 as arguments. Assign the return + // value to the total variable. + total = sum(value1, value2); + + // Display the sum of the values. + cout << "The sum of " << value1 << " and " + << value2 << " is " << total << endl; + return 0; +} + +//***************************************************** +// Definition of function sum. This function returns * +// the sum of its two parameters. * +//***************************************************** + +int sum(int num1, int num2) +{ + return num1 + num2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-13.cpp b/SourceCode/Chapter 06/Pr6-13.cpp new file mode 100755 index 0000000..5c10e21 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-13.cpp @@ -0,0 +1,57 @@ +// This program demonstrates two value-returning functions. +// The square function is called in a mathematical statement. +#include +#include +using namespace std; + +//Function prototypes +double getRadius(); +double square(double); + +int main() +{ + const double PI = 3.14159; // Constant for pi + double radius; // To hold the circle's radius + double area; // To hold the circle's area + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Get the radius of the circle. + cout << "This program calculates the area of "; + cout << "a circle.\n"; + radius = getRadius(); + + // Caclulate the area of the circle. + area = PI * square(radius); + + // Display the area. + cout << "The area is " << area << endl; + return 0; +} + +//****************************************************** +// Definition of function getRadius. * +// This function asks the user to enter the radius of * +// the circle and then returns that number as a double.* +//****************************************************** + +double getRadius() +{ + double rad; + + cout << "Enter the radius of the circle: "; + cin >> rad; + return rad; +} + +//****************************************************** +// Definition of function square. * +// This function accepts a double argument and returns * +// the square of the argument as a double. * +//****************************************************** + +double square(double number) +{ + return number * number; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-14.cpp b/SourceCode/Chapter 06/Pr6-14.cpp new file mode 100755 index 0000000..d5e626a --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-14.cpp @@ -0,0 +1,73 @@ +// This program converts cups to fluid ounces. +#include +#include +using namespace std; + +// Function prototypes +void showIntro(); +double getCups(); +double cupsToOunces(double); + +int main() +{ + // Variables for the cups and ounces. + double cups, ounces; + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Display an intro screen. + showIntro(); + + // Get the number of cups. + cups = getCups(); + + // Convert cups to fluid ounces. + ounces = cupsToOunces(cups); + + // Display the number of ounces. + cout << cups << " cups equals " + << ounces << " ounces.\n"; + + return 0; +} + +//****************************************** +// The showIntro function displays an * +// introductory screen. * +//****************************************** + +void showIntro() +{ + cout << "This program converts measurements\n" + << "in cups to fluid ounces. For your\n" + << "reference the formula is:\n" + << " 1 cup = 8 fluid ounces\n\n"; +} + +//****************************************** +// The getCups function prompts the user * +// to enter the number of cups and then * +// returns that value as a double. * +//****************************************** + +double getCups() +{ + double numCups; + + cout << "Enter the number of cups: "; + cin >> numCups; + return numCups; +} + +//****************************************** +// The cupsToOunces function accepts a * +// number of cups as an argument and * +// returns the equivalent number of fluid * +// ounces as a double. * +//****************************************** + +double cupsToOunces(double numCups) +{ + return numCups * 8.0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-15.cpp b/SourceCode/Chapter 06/Pr6-15.cpp new file mode 100755 index 0000000..3c5949c --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-15.cpp @@ -0,0 +1,41 @@ +// This program uses a function that returns true or false. +#include +using namespace std; + +// Function prototype +bool isEven(int); + +int main() +{ + int val; + + // Get a number from the user. + cout << "Enter an integer and I will tell you "; + cout << "if it is even or odd: "; + cin >> val; + + // Indicate whether it is even or odd. + if (isEven(val)) + cout << val << " is even.\n"; + else + cout << val << " is odd.\n"; + return 0; +} + +//***************************************************************** +// Definition of function isEven. This function accepts an * +// integer argument and tests it to be even or odd. The function * +// returns true if the argument is even or false if the argument * +// is odd. The return value is an bool. * +//***************************************************************** + +bool isEven(int number) +{ + bool status; + + if (number % 2 == 0) + status = true; // number is even if there is no remainder. + else + status = false; // Otherwise, the number is odd. + return status; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-16.cpp b/SourceCode/Chapter 06/Pr6-16.cpp new file mode 100755 index 0000000..fa793d3 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-16.cpp @@ -0,0 +1,29 @@ +// This program shows that variables defined in a function +// are hidden from other functions. +#include +using namespace std; + +void anotherFunction(); // Function prototype + +int main() +{ + int num = 1; // Local variable + + cout << "In main, num is " << num << endl; + anotherFunction(); + cout << "Back in main, num is " << num << endl; + return 0; +} + +//***************************************************** +// Definition of anotherFunction * +// It has a local variable, num, whose initial value * +// is displayed. * +//***************************************************** + +void anotherFunction() +{ + int num = 20; // Local variable + + cout << "In anotherFunction, num is " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-17.cpp b/SourceCode/Chapter 06/Pr6-17.cpp new file mode 100755 index 0000000..000817d --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-17.cpp @@ -0,0 +1,29 @@ +// This program shows that a global variable is visible +// to all the functions that appear in a program after +// the variable's declaration. +#include +using namespace std; + +void anotherFunction(); // Function prototype +int num = 2; // Global variable + +int main() +{ + cout << "In main, num is " << num << endl; + anotherFunction(); + cout << "Back in main, num is " << num << endl; + return 0; +} + +//***************************************************** +// Definition of anotherFunction * +// This function changes the value of the * +// global variable num. * +//***************************************************** + +void anotherFunction() +{ + cout << "In anotherFunction, num is " << num << endl; + num = 50; + cout << "But, it is now changed to " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-18.cpp b/SourceCode/Chapter 06/Pr6-18.cpp new file mode 100755 index 0000000..a99966a --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-18.cpp @@ -0,0 +1,11 @@ +// This program has an uninitialized global variable. +#include +using namespace std; + +int globalNum; // Global variable, automatically set to zero + +int main() +{ + cout << "globalNum is " << globalNum << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-19.cpp b/SourceCode/Chapter 06/Pr6-19.cpp new file mode 100755 index 0000000..bf0b9b8 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-19.cpp @@ -0,0 +1,85 @@ +// This program calculates gross pay. +#include +#include +using namespace std; + +// Global constants +const double PAY_RATE = 22.55; // Hourly pay rate +const double BASE_HOURS = 40.0; // Max non-overtime hours +const double OT_MULTIPLIER = 1.5; // Overtime multiplier + +// Function prototypes +double getBasePay(double); +double getOvertimePay(double); + +int main() +{ + double hours, // Hours worked + basePay, // Base pay + overtime = 0.0, // Overtime pay + totalPay; // Total pay + + // Get the number of hours worked. + cout << "How many hours did you work? "; + cin >> hours; + + // Get the amount of base pay. + basePay = getBasePay(hours); + + // Get overtime pay, if any. + if (hours > BASE_HOURS) + overtime = getOvertimePay(hours); + + // Calculate the total pay. + totalPay = basePay + overtime; + + // Set up numeric output formatting. + cout << setprecision(2) << fixed << showpoint; + + // Display the pay. + cout << "Base pay: $" << basePay << endl + << "Overtime pay $" << overtime << endl + << "Total pay $" << totalPay << endl; + return 0; +} + +//************************************************ +// The getBasePay function accepts the number of * +// hours worked as an argument and returns the * +// employee's pay for non-overtime hours. * +//************************************************ + +double getBasePay(double hoursWorked) +{ + double basePay; // To hold base pay + + // Determine base pay. + if (hoursWorked > BASE_HOURS) + basePay = BASE_HOURS * PAY_RATE; + else + basePay = hoursWorked * PAY_RATE; + + return basePay; +} + +//************************************************* +// The getOvertimePay function accepts the number * +// of hours worked as an argument and returns the * +// employee's overtime pay. * +//************************************************* + +double getOvertimePay(double hoursWorked) +{ + double overtimePay; // To hold overtime pay + + // Determine overtime pay. + if (hoursWorked > BASE_HOURS) + { + overtimePay = (hoursWorked - BASE_HOURS) * + PAY_RATE * OT_MULTIPLIER; + } + else + overtimePay = 0.0; + + return overtimePay; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-2.cpp b/SourceCode/Chapter 06/Pr6-2.cpp new file mode 100755 index 0000000..ea3eb61 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-2.cpp @@ -0,0 +1,26 @@ +// The function displayMessage is repeatedly called from a loop. +#include +using namespace std; + +//***************************************** +// Definition of function displayMessage * +// This function displays a greeting. * +//***************************************** + +void displayMessage() +{ + cout << "Hello from the function displayMessage.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "Hello from main.\n"; + for (int count = 0; count < 5; count++) + displayMessage(); // Call displayMessage + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-20.cpp b/SourceCode/Chapter 06/Pr6-20.cpp new file mode 100755 index 0000000..3cb4f2b --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-20.cpp @@ -0,0 +1,29 @@ +// This program demonstrates how a local variable +// can shadow the name of a global constant. +#include +using namespace std; + +// Gobal constant. +const int BIRDS = 500; + +// Function prototype +void california(); + +int main() +{ + cout << "In main there are " << BIRDS + << " birds.\n"; + california(); + return 0; +} + +//******************************************** +// california function * +//******************************************** + +void california() +{ + const int BIRDS = 10000; + cout << "In california there are " << BIRDS + << " birds.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-21.cpp b/SourceCode/Chapter 06/Pr6-21.cpp new file mode 100755 index 0000000..20c61df --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-21.cpp @@ -0,0 +1,29 @@ +// This program shows that local variables do not retain +// their values between function calls. +#include +using namespace std; + +// Function prototype +void showLocal(); + +int main() +{ + showLocal(); + showLocal(); + return 0; +} + +//*********************************************************** +// Definition of function showLocal. * +// The initial value of localNum, which is 5, is displayed. * +// The value of localNum is then changed to 99 before the * +// function returns. * +//*********************************************************** + +void showLocal() +{ + int localNum = 5; // Local variable + + cout << "localNum is " << localNum << endl; + localNum = 99; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-22.cpp b/SourceCode/Chapter 06/Pr6-22.cpp new file mode 100755 index 0000000..c84d43c --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-22.cpp @@ -0,0 +1,27 @@ +// This program uses a static local variable. +#include +using namespace std; + +void showStatic(); // Function prototype + +int main() +{ + // Call the showStatic function five times. + for (int count = 0; count < 5; count++) + showStatic(); + return 0; +} + +//************************************************************** +// Definition of function showStatic. * +// statNum is a static local variable. Its value is displayed * +// and then incremented just before the function returns. * +//************************************************************** + +void showStatic() +{ + static int statNum; + + cout << "statNum is " << statNum << endl; + statNum++; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-23.cpp b/SourceCode/Chapter 06/Pr6-23.cpp new file mode 100755 index 0000000..f1aae8b --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-23.cpp @@ -0,0 +1,28 @@ +// This program shows that a static local variable is only +// initialized once. +#include +using namespace std; + +void showStatic(); // Function prototype + +int main() +{ + // Call the showStatic function five times. + for (int count = 0; count < 5; count++) + showStatic(); + return 0; +} + +//************************************************************** +// Definition of function showStatic. * +// statNum is a static local variable. Its value is displayed * +// and then incremented just before the function returns. * +//************************************************************** + +void showStatic() +{ + static int statNum = 5; + + cout << "statNum is " << statNum << endl; + statNum++; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-24.cpp b/SourceCode/Chapter 06/Pr6-24.cpp new file mode 100755 index 0000000..241ea38 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-24.cpp @@ -0,0 +1,34 @@ +// This program demonstrates default function arguments. +#include +using namespace std; + +// Function prototype with default arguments +void displayStars(int = 10, int = 1); + +int main() +{ + displayStars(); // Use default values for cols and rows. + cout << endl; + displayStars(5); // Use default value for rows. + cout << endl; + displayStars(7, 3); // Use 7 for cols and 3 for rows. + return 0; +} + +//******************************************************** +// Definition of function displayStars. * +// The default argument for cols is 10 and for rows is 1.* +// This function displays a square made of asterisks. * +//******************************************************** + +void displayStars(int cols, int rows) +{ + // Nested loop. The outer loop controls the rows + // and the inner loop controls the columns. + for (int down = 0; down < rows; down++) + { + for (int across = 0; across < cols; across++) + cout << "*"; + cout << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-25.cpp b/SourceCode/Chapter 06/Pr6-25.cpp new file mode 100755 index 0000000..e2e722c --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-25.cpp @@ -0,0 +1,29 @@ +// This program uses a reference variable as a function +// parameter. +#include +using namespace std; + +// Function prototype. The parameter is a reference variable. +void doubleNum(int &); + +int main() +{ + int value = 4; + + cout << "In main, value is " << value << endl; + cout << "Now calling doubleNum..." << endl; + doubleNum(value); + cout << "Now back in main. value is " << value << endl; + return 0; +} + +//********************************************************** +// Definition of doubleNum. * +// The parameter refVar is a reference variable. The value * +// in refVar is doubled. * +//********************************************************** + +void doubleNum (int &refVar) +{ + refVar *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-26.cpp b/SourceCode/Chapter 06/Pr6-26.cpp new file mode 100755 index 0000000..88aeff8 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-26.cpp @@ -0,0 +1,46 @@ +// This program uses reference variables as function parameters. +#include +using namespace std; + +// Function prototypes. Both functions use reference variables +// as parameters. +void doubleNum(int &); +void getNum(int &); + +int main() +{ + int value; + + // Get a number and store it in value. + getNum(value); + + // Double the number stored in value. + doubleNum(value); + + // Display the resulting number. + cout << "That value doubled is " << value << endl; + return 0; +} + +//************************************************************* +// Definition of getNum. * +// The parameter userNum is a reference variable. The user is * +// asked to enter a number, which is stored in userNum. * +//************************************************************* + +void getNum(int &userNum) +{ + cout << "Enter a number: "; + cin >> userNum; +} + +//********************************************************** +// Definition of doubleNum. * +// The parameter refVar is a reference variable. The value * +// in refVar is doubled. * +//********************************************************** + +void doubleNum (int &refVar) +{ + refVar *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-27.cpp b/SourceCode/Chapter 06/Pr6-27.cpp new file mode 100755 index 0000000..7f209cb --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-27.cpp @@ -0,0 +1,46 @@ +// This program uses overloaded functions. +#include +#include +using namespace std; + +// Function prototypes +int square(int); +double square(double); + +int main() +{ + int userInt; + double userFloat; + + // Get an int and a double. + cout << fixed << showpoint << setprecision(2); + cout << "Enter an integer and a floating-point value: "; + cin >> userInt >> userFloat; + + // Display their squares. + cout << "Here are their squares: "; + cout << square(userInt) << " and " << square(userFloat); + return 0; +} + +//************************************************************** +// Definition of overloaded function square. * +// This function uses an int parameter, number. It returns the * +// square of number as an int. * +//************************************************************** + +int square(int number) +{ + return number * number; +} + +//*************************************************************** +// Definition of overloaded function square. * +// This function uses a double parameter, number. It returns * +// the square of number as a double. * +//*************************************************************** + +double square(double number) +{ + return number * number; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-28.cpp b/SourceCode/Chapter 06/Pr6-28.cpp new file mode 100755 index 0000000..4dc5d8d --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-28.cpp @@ -0,0 +1,97 @@ +// This program demonstrates overloaded functions to calculate +// the gross weekly pay of hourly-paid or salaried employees. +#include +#include +using namespace std; + +// Function prototypes +void getChoice(char &); +double calcWeeklyPay(int, double); +double calcWeeklyPay(double); + +int main() +{ + char selection; // Menu selection + int worked; // Hours worked + double rate; // Hourly pay rate + double yearly; // Yearly salary + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the menu and get a selection. + cout << "Do you want to calculate the weekly pay of\n"; + cout << "(H) an hourly-paid employee, or \n"; + cout << "(S) a salaried employee?\n"; + getChoice(selection); + + // Process the menu selection. + switch (selection) + { + // Hourly-paid employee + case 'H' : + case 'h' : cout << "How many hours were worked? "; + cin >> worked; + cout << "What is the hour pay rate? "; + cin >> rate; + cout << "The gross weekly pay is $"; + cout << calcWeeklyPay(worked, rate) << endl; + break; + + // Salaried employee + case 'S' : + case 's' : cout << "What is the annual salary? "; + cin >> yearly; + cout << "The gross weekly pay is $"; + cout << calcWeeklyPay(yearly) << endl; + break; + } + return 0; +} + +//************************************************************* +// Definition of function getChoice. * +// The parameter letter is a reference to a char. * +// This function asks the user for an H or an S and returns * +// the validated input. * +//************************************************************* + +void getChoice(char &letter) +{ + // Get the user's selection. + cout << "Enter your choice (H or S): "; + cin >> letter; + + // Validate the selection. + while (letter != 'H' && letter != 'h' && + letter != 'S' && letter != 's') + { + cout << "Please enter H or S: "; + cin >> letter; + } +} + +//*********************************************************** +// Definition of overloaded function calcWeeklyPay. * +// This function calculates the gross weekly pay of * +// an hourly-paid employee. The parameter hours holds the * +// number of hours worked. The parameter payRate holds the * +// hourly pay rate. The function returns the weekly salary. * +//*********************************************************** + +double calcWeeklyPay(int hours, double payRate) +{ + return hours * payRate; +} + +//*********************************************************** +// Definition of overloaded function calcWeeklyPay. * +// This function calculates the gross weekly pay of * +// a salaried employee. The parameter holds the employee's * +// annual salary. The function returns the weekly salary. * +//*********************************************************** + +double calcWeeklyPay(double annSalary) +{ + return annSalary / 52; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-29.cpp b/SourceCode/Chapter 06/Pr6-29.cpp new file mode 100755 index 0000000..231cff7 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-29.cpp @@ -0,0 +1,27 @@ +// This program shows how the exit function causes a program +// to stop executing. +#include +#include // Needed for the exit function +using namespace std; + +void function(); // Function prototype + +int main() +{ + function(); + return 0; +} + +//*********************************************************** +// This function simply demonstrates that exit can be used * +// to terminate a program from a function other than main. * +//*********************************************************** + +void function() +{ + cout << "This program terminates with the exit function.\n"; + cout << "Bye!\n"; + exit(0); + cout << "This message will never be displayed\n"; + cout << "because the program has already terminated.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-3.cpp b/SourceCode/Chapter 06/Pr6-3.cpp new file mode 100755 index 0000000..466c742 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-3.cpp @@ -0,0 +1,36 @@ +// This program has three functions: main, first, and second. +#include +using namespace std; + +//***************************************** +// Definition of function first * +// This function displays a message. * +//***************************************** + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//***************************************** +// Definition of function second * +// This function displays a message. * +//***************************************** + +void second() +{ + cout << "I am now inside the function second.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-30.cpp b/SourceCode/Chapter 06/Pr6-30.cpp new file mode 100755 index 0000000..99a7a61 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-30.cpp @@ -0,0 +1,45 @@ +// This program is a driver for testing the showFees function. +#include +using namespace std; + +// Prototype +void showFees(double, int); + +int main() +{ + // Constants for membership rates + const double ADULT = 40.0; + const double SENIOR = 30.0; + const double CHILD = 20.0; + + // Perform a test for adult membership. + cout << "Testing an adult membership...\n" + << "Calling the showFees function with arguments " + << ADULT << " and 10.\n"; + showFees(ADULT, 10); + + // Perform a test for senior citizen membership. + cout << "\nTesting a senior citizen membership...\n" + << "Calling the showFees function with arguments " + << SENIOR << " and 10.\n"; + showFees(SENIOR, 10); + + // Perform a test for child membership. + cout << "\nTesting a child membership...\n" + << "\nCalling the showFees function with arguments " + << CHILD << " and 10.\n"; + showFees(CHILD, 10); + return 0; +} + +//***************************************************************** +// Definition of function showFees. The memberRate parameter * +// the monthly membership rate and the months parameter holds the * +// number of months. The function displays the total charges. * +//***************************************************************** + +void showFees(double memberRate, int months) +{ + cout << "The total charges are $" + << (memberRate * months) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-4.cpp b/SourceCode/Chapter 06/Pr6-4.cpp new file mode 100755 index 0000000..210d371 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-4.cpp @@ -0,0 +1,37 @@ +// This program has three functions: main, deep, and deeper +#include +using namespace std; + +//***************************************** +// Definition of function deeper * +// This function displays a message. * +//***************************************** + +void deeper() +{ + cout << "I am now inside the function deeper.\n"; +} + +//***************************************** +// Definition of function deep * +// This function displays a message. * +//***************************************** + +void deep() +{ + cout << "I am now inside the function deep.\n"; + deeper(); // Call function deeper + cout << "Now I am back in deep.\n"; +} + +//***************************************** +// Function main * +//***************************************** + +int main() +{ + cout << "I am starting in function main.\n"; + deep(); // Call function deep + cout << "Back in function main again.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-5.cpp b/SourceCode/Chapter 06/Pr6-5.cpp new file mode 100755 index 0000000..352c6b4 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-5.cpp @@ -0,0 +1,36 @@ +// This program has three functions: main, first, and second. +#include +using namespace std; + +// Function Prototypes +void first(); +void second(); + +int main() +{ + cout << "I am starting in function main.\n"; + first(); // Call function first + second(); // Call function second + cout << "Back in function main again.\n"; + return 0; +} + +//************************************* +// Definition of function first. * +// This function displays a message. * +//************************************* + +void first() +{ + cout << "I am now inside the function first.\n"; +} + +//************************************* +// Definition of function second. * +// This function displays a message. * +//************************************* + +void second() +{ + cout << "I am now inside the function second.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-6.cpp b/SourceCode/Chapter 06/Pr6-6.cpp new file mode 100755 index 0000000..33013c3 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-6.cpp @@ -0,0 +1,24 @@ +// This program demonstrates a function with a parameter. +#include +using namespace std; + +// Function Prototype +void displayValue(int); + +int main() +{ + cout << "I am passing 5 to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + cout << "Now I am back in main.\n"; + return 0; +} + +//********************************************************* +// Definition of function displayValue. * +// It uses an integer parameter whose value is displayed. * +//********************************************************* + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-7.cpp b/SourceCode/Chapter 06/Pr6-7.cpp new file mode 100755 index 0000000..e0ba586 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-7.cpp @@ -0,0 +1,27 @@ +// This program demonstrates a function with a parameter. +#include +using namespace std; + +// Function Prototype +void displayValue(int); + +int main() +{ + cout << "I am passing several values to displayValue.\n"; + displayValue(5); // Call displayValue with argument 5 + displayValue(10); // Call displayValue with argument 10 + displayValue(2); // Call displayValue with argument 2 + displayValue(16); // Call displayValue with argument 16 + cout << "Now I am back in main.\n"; + return 0; +} + +//********************************************************* +// Definition of function displayValue. * +// It uses an integer parameter whose value is displayed. * +//********************************************************* + +void displayValue(int num) +{ + cout << "The value is " << num << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-8.cpp b/SourceCode/Chapter 06/Pr6-8.cpp new file mode 100755 index 0000000..4015496 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-8.cpp @@ -0,0 +1,30 @@ +// This program demonstrates a function with three parameters. +#include +using namespace std; + +// Function Prototype +void showSum(int, int, int); + +int main() +{ + int value1, value2, value3; + + // Get three integers. + cout << "Enter three integers and I will display "; + cout << "their sum: "; + cin >> value1 >> value2 >> value3; + + // Call showSum passing three arguments. + showSum(value1, value2, value3); + return 0; +} + +//************************************************************ +// Definition of function showSum. * +// It uses three integer parameters. Their sum is displayed. * +//************************************************************ + +void showSum(int num1, int num2, int num3) +{ + cout << (num1 + num2 + num3) << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 06/Pr6-9.cpp b/SourceCode/Chapter 06/Pr6-9.cpp new file mode 100755 index 0000000..02eeb99 --- /dev/null +++ b/SourceCode/Chapter 06/Pr6-9.cpp @@ -0,0 +1,38 @@ +// This program demonstrates that changes to a function parameter +// have no affect on the original argument. +#include +using namespace std; + +// Function Prototype +void changeMe(int); + +int main() +{ + int number = 12; + + // Display the value in number. + cout << "number is " << number << endl; + + // Call changeMe, passing the value in number + // as an argument. + changeMe(number); + + // Display the value in number again. + cout << "Now back in main again, the value of "; + cout << "number is " << number << endl; + return 0; +} + +//************************************************************** +// Definition of function changeMe. * +// This function changes the value of the parameter myValue. * +//************************************************************** + +void changeMe(int myValue) +{ + // Change the value of myValue to 0. + myValue = 0; + + // Display the value in myValue. + cout << "Now the value is " << myValue << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-1.cpp b/SourceCode/Chapter 07/Pr7-1.cpp new file mode 100755 index 0000000..da32ef6 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-1.cpp @@ -0,0 +1,30 @@ +// This program asks for the number of hours worked +// by six employees. It stores the values in an array. +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 6; + int hours[NUM_EMPLOYEES]; + + // Get the hours worked by each employee. + cout << "Enter the hours worked by " + << NUM_EMPLOYEES << " employees: "; + cin >> hours[0]; + cin >> hours[1]; + cin >> hours[2]; + cin >> hours[3]; + cin >> hours[4]; + cin >> hours[5]; + + // Display the values in the array. + cout << "The hours you entered are:"; + cout << " " << hours[0]; + cout << " " << hours[1]; + cout << " " << hours[2]; + cout << " " << hours[3]; + cout << " " << hours[4]; + cout << " " << hours[5] << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-10.cpp b/SourceCode/Chapter 07/Pr7-10.cpp new file mode 100755 index 0000000..bd1274d --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-10.cpp @@ -0,0 +1,15 @@ +// This program demonstrates the range-based for loop. +#include +using namespace std; + +int main() +{ + // Define an array of integers. + int numbers[] = { 10, 20, 30, 40, 50 }; + + // Display the values in the array. + for (auto val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-11.cpp b/SourceCode/Chapter 07/Pr7-11.cpp new file mode 100755 index 0000000..5b4056f --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-11.cpp @@ -0,0 +1,19 @@ +// This program demonstrates the range-based for loop. +#include +#include +using namespace std; + +int main() +{ + string planets[] = { "Mercury", "Venus", "Earth", "Mars", + "Jupiter", "Saturn", "Uranus", + "Neptune", "Pluto (a dwarf planet)" }; + + cout << "Here are the planets:\n"; + + // Display the values in the array. + for (auto val : planets) + cout << val << endl; + + return 0; +} diff --git a/SourceCode/Chapter 07/Pr7-12.cpp b/SourceCode/Chapter 07/Pr7-12.cpp new file mode 100755 index 0000000..da966e5 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-12.cpp @@ -0,0 +1,24 @@ +// This program uses a range-based for loop to +// modify the contents of an array. +#include +using namespace std; + +int main() +{ + const int SIZE = 5; + int numbers[5]; + + // Get values for the array. + for (auto &val : numbers) + { + cout << "Enter an integer value: "; + cin >> val; + } + + // Display the values in the array. + cout << "Here are the values you entered:\n"; + for (auto val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-13.cpp b/SourceCode/Chapter 07/Pr7-13.cpp new file mode 100755 index 0000000..8a4c946 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-13.cpp @@ -0,0 +1,38 @@ +// This program stores, in an array, the hours worked by +// employees who all make the same hourly wage. +#include +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + int hours[NUM_EMPLOYEES]; // Array to hold hours + double payrate; // Hourly pay rate + double grossPay; // To hold the gross pay + + // Input the hours worked. + cout << "Enter the hours worked by "; + cout << NUM_EMPLOYEES << " employees who all\n"; + cout << "earn the same hourly rate.\n"; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Employee #" << (index + 1) << ": "; + cin >> hours[index]; + } + + // Input the hourly rate for all employees. + cout << "Enter the hourly pay rate for all the employees: "; + cin >> payrate; + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + grossPay = hours[index] * payrate; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-14.cpp b/SourceCode/Chapter 07/Pr7-14.cpp new file mode 100755 index 0000000..de39237 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-14.cpp @@ -0,0 +1,30 @@ +// This program reads data from a file into an array. +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 100; // Array size + int numbers[ARRAY_SIZE]; // Array with 100 elements + int count = 0; // Loop counter variable + ifstream inputFile; // Input file stream object + + inputFile.open("numbers.txt"); // Open the file. + + // Read the numbers from the file into the array. + // After this loop executes, the count variable will hold + // the number of values that were stored in the array. + while (count < ARRAY_SIZE && inputFile >> numbers[count]) + count++; + + // Close the file. + inputFile.close(); + + // Display the numbers read. + cout << "The numbers are: "; + for (int index = 0; index < count; index++) + cout << numbers[index] << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-15.cpp b/SourceCode/Chapter 07/Pr7-15.cpp new file mode 100755 index 0000000..42f4176 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-15.cpp @@ -0,0 +1,35 @@ +// This program uses two parallel arrays: one for hours +// worked and one for pay rate. +#include +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + int hours[NUM_EMPLOYEES]; // Holds hours worked + double payRate[NUM_EMPLOYEES]; // Holds pay rates + + // Input the hours worked and the hourly pay rate. + cout << "Enter the hours worked by " << NUM_EMPLOYEES + << " employees and their\n" + << "hourly pay rates.\n"; + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Hours worked by employee #" << (index+1) << ": "; + cin >> hours[index]; + cout << "Hourly pay rate for employee #" << (index+1) << ": "; + cin >> payRate[index]; + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (int index = 0; index < NUM_EMPLOYEES; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-16.cpp b/SourceCode/Chapter 07/Pr7-16.cpp new file mode 100755 index 0000000..586e091 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-16.cpp @@ -0,0 +1,27 @@ +// This program demonstrates that an array element is passed +// to a function like any other variable. +#include +using namespace std; + +void showValue(int); // Function prototype + +int main() +{ + const int SIZE = 8; + int numbers[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + + for (int index = 0; index < SIZE; index++) + showValue(numbers[index]); + return 0; +} + +//********************************************** +// Definition of function showValue. * +// This function accepts an integer argument. * +// The value of the argument is displayed. * +//********************************************** + +void showValue(int num) +{ + cout << num << " "; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-17.cpp b/SourceCode/Chapter 07/Pr7-17.cpp new file mode 100755 index 0000000..aba9e1b --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-17.cpp @@ -0,0 +1,28 @@ +// This program demonstrates an array being passed to a function. +#include +using namespace std; + +void showValues(int [], int); // Function prototype + +int main() +{ + const int ARRAY_SIZE = 8; + int numbers[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + + showValues(numbers, ARRAY_SIZE); + return 0; +} + +//************************************************** +// Definition of function showValue. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + cout << nums[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-18.cpp b/SourceCode/Chapter 07/Pr7-18.cpp new file mode 100755 index 0000000..c82b29d --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-18.cpp @@ -0,0 +1,35 @@ +// This program demonstrates the showValues function being +// used to display the contents of two arrays. +#include +using namespace std; + +void showValues(int [], int); // Function prototype + +int main() +{ + const int SIZE1 = 8; // Size of set1 array + const int SIZE2 = 5; // Size of set2 array + int set1[SIZE1] = {5, 10, 15, 20, 25, 30, 35, 40}; + int set2[SIZE2] = {2, 4, 6, 8, 10}; + + // Pass set1 to showValues. + showValues(set1, SIZE1); + + // Pass set2 to showValues. + showValues(set2, SIZE2); + return 0; +} + +//************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + cout << nums[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-19.cpp b/SourceCode/Chapter 07/Pr7-19.cpp new file mode 100755 index 0000000..c19bfc6 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-19.cpp @@ -0,0 +1,54 @@ +// This program uses a function to double the value of +// each element of an array. +#include +using namespace std; + +// Function prototypes +void doubleArray(int [], int); +void showValues(int [], int); + +int main() +{ + const int ARRAY_SIZE = 7; + int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7}; + + // Display the initial values. + cout << "The arrays values are:\n"; + showValues(set, ARRAY_SIZE); + + // Double the values in the array. + doubleArray(set, ARRAY_SIZE); + + // Display the resulting values. + cout << "After calling doubleArray the values are:\n"; + showValues(set, ARRAY_SIZE); + + return 0; +} + +//***************************************************** +// Definition of function doubleArray * +// This function doubles the value of each element * +// in the array passed into nums. The value passed * +// into size is the number of elements in the array. * +//***************************************************** + +void doubleArray(int nums[], int size) +{ + for (int index = 0; index < size; index++) + nums[index] *= 2; +} + +//************************************************** +// Definition of function showValues. * +// This function accepts an array of integers and * +// the array's size as its arguments. The contents * +// of the array are displayed. * +//************************************************** + +void showValues(int nums[], int size) +{ + for (int index = 0; index < size; index++) + cout << nums[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-2.cpp b/SourceCode/Chapter 07/Pr7-2.cpp new file mode 100755 index 0000000..b39da6e --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-2.cpp @@ -0,0 +1,26 @@ +// This program asks for the number of hours worked +// by six employees. It stores the values in an array. +#include +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 6; // Number of employees + int hours[NUM_EMPLOYEES]; // Each employee's hours + int count; // Loop counter + + // Input the hours worked. + for (count = 0; count < NUM_EMPLOYEES; count++) + { + cout << "Enter the hours worked by employee " + << (count + 1) << ": "; + cin >> hours[count]; + } + + // Display the contents of the array. + cout << "The hours you entered are:"; + for (count = 0; count < NUM_EMPLOYEES; count++) + cout << " " << hours[count]; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-20.cpp b/SourceCode/Chapter 07/Pr7-20.cpp new file mode 100755 index 0000000..0906879 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-20.cpp @@ -0,0 +1,109 @@ +// This program gets a series of test scores and +// calculates the average of the scores with the +// lowest score dropped. +#include +#include +using namespace std; + +// Function prototypes +void getTestScores(double[], int); +double getTotal(const double[], int); +double getLowest(const double[], int); + +int main() +{ + const int SIZE = 4; // Array size + double testScores[SIZE], // Array of test scores + total, // Total of the scores + lowestScore, // Lowest test score + average; // Average test score + + // Set up numeric output formatting. + cout << fixed << showpoint << setprecision(1); + + // Get the test scores from the user. + getTestScores(testScores, SIZE); + + // Get the total of the test scores. + total = getTotal(testScores, SIZE); + + // Get the lowest test score. + lowestScore = getLowest(testScores, SIZE); + + // Subtract the lowest score from the total. + total -= lowestScore; + + // Calculate the average. Divide by 3 because + // the lowest test score was dropped. + average = total / (SIZE - 1); + + // Display the average. + cout << "The average with the lowest score " + << "dropped is " << average << ".\n"; + + return 0; +} + +//************************************************************ +// The getTestScores function accepts an array and its size * +// as arguments. It prompts the user to enter test scores, * +// which are stored in the array. * +//************************************************************ + +void getTestScores(double scores[], int size) +{ + // Loop counter + int index; + + // Get each test score. + for(index = 0; index <= size - 1; index++) + { + cout << "Enter test score number " + << (index + 1) << ": "; + cin >> scores[index]; + } +} + +//**************************************************** +// The getTotal function accepts a double array * +// and its size as arguments. The sum of the array's * +// elements is returned as a double. * +//**************************************************** + +double getTotal(const double array[], int size) +{ + double total = 0; // Accumulator + + // Add each element to total. + for (int count = 0; count < size; count++) + total += array[count]; + + // Return the total. + return total; +} + +//**************************************************** +// The getLowest function accepts a double array and * +// its size as arguments. The lowest value in the * +// array is returned as a double. * +//**************************************************** + +double getLowest(const double array[], int size) +{ + double lowest; // To hold the lowest value + + // Get the first array's first element. + lowest = array[0]; + + // Step through the rest of the array. When a + // value less than lowest is found, assign it + // to lowest. + for (int count = 1; count < size; count++) + { + if (array[count] < lowest) + lowest = array[count]; + } + + // Return the lowest value. + return lowest; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-21.cpp b/SourceCode/Chapter 07/Pr7-21.cpp new file mode 100755 index 0000000..31ecf9d --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-21.cpp @@ -0,0 +1,42 @@ +// This program demonstrates a two-dimensional array. +#include +#include +using namespace std; + +int main() +{ + const int NUM_DIVS = 3; // Number of divisions + const int NUM_QTRS = 4; // Number of quarters + double sales[NUM_DIVS][NUM_QTRS]; // Array with 3 rows and 4 columns. + double totalSales = 0; // To hold the total sales. + int div, qtr; // Loop counters. + + cout << "This program will calculate the total sales of\n"; + cout << "all the company's divisions.\n"; + cout << "Enter the following sales information:\n\n"; + + // Nested loops to fill the array with quarterly + // sales figures for each division. + for (div = 0; div < NUM_DIVS; div++) + { + for (qtr = 0; qtr < NUM_QTRS; qtr++) + { + cout << "Division " << (div + 1); + cout << ", Quarter " << (qtr + 1) << ": $"; + cin >> sales[div][qtr]; + } + cout << endl; // Print blank line. + } + + // Nested loops used to add all the elements. + for (div = 0; div < NUM_DIVS; div++) + { + for (qtr = 0; qtr < NUM_QTRS; qtr++) + totalSales += sales[div][qtr]; + } + + cout << fixed << showpoint << setprecision(2); + cout << "The total sales for the company are: $"; + cout << totalSales << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-22.cpp b/SourceCode/Chapter 07/Pr7-22.cpp new file mode 100755 index 0000000..baee1c3 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-22.cpp @@ -0,0 +1,47 @@ +// This program demonstrates accepting a 2D array argument. +#include +#include +using namespace std; + +// Global constants +const int COLS = 4; // Number of columns in each array +const int TBL1_ROWS = 3; // Number of rows in table1 +const int TBL2_ROWS = 4; // Number of rows in table2 + +void showArray(const int [][COLS], int); // Function prototype + +int main() +{ + int table1[TBL1_ROWS][COLS] = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}}; + int table2[TBL2_ROWS][COLS] = {{10, 20, 30, 40}, + {50, 60, 70, 80}, + {90, 100, 110, 120}, + {130, 140, 150, 160}}; + + cout << "The contents of table1 are:\n"; + showArray(table1, TBL1_ROWS); + cout << "The contents of table2 are:\n"; + showArray(table2, TBL2_ROWS); + return 0; +} + +//***************************************************************** +// Function Definition for showArray * +// The first argument is a two-dimensional int array with COLS * +// columns. The second argument, rows, specifies the number of * +// rows in the array. The function displays the array's contents. * +//***************************************************************** + +void showArray(const int array[][COLS], int rows) +{ + for (int x = 0; x < rows; x++) + { + for (int y = 0; y < COLS; y++) + { + cout << setw(4) << array[x][y] << " "; + } + cout << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-23.cpp b/SourceCode/Chapter 07/Pr7-23.cpp new file mode 100755 index 0000000..579340b --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-23.cpp @@ -0,0 +1,48 @@ +// This program is a driver that tests a function comparing the +// contents of two int arrays. +#include +using namespace std; + +// Function Prototype +bool testPIN(const int [], const int [], int); + +int main () +{ + const int NUM_DIGITS = 7; // Number of digits in a PIN + int pin1[NUM_DIGITS] = {2, 4, 1, 8, 7, 9, 0}; // Base set of values. + int pin2[NUM_DIGITS] = {2, 4, 6, 8, 7, 9, 0}; // Only 1 element is + // different from pin1. + int pin3[NUM_DIGITS] = {1, 2, 3, 4, 5, 6, 7}; // All elements are + // different from pin1. + if (testPIN(pin1, pin2, NUM_DIGITS)) + cout << "ERROR: pin1 and pin2 report to be the same.\n"; + else + cout << "SUCCESS: pin1 and pin2 are different.\n"; + + if (testPIN(pin1, pin3, NUM_DIGITS)) + cout << "ERROR: pin1 and pin3 report to be the same.\n"; + else + cout << "SUCCESS: pin1 and pin3 are different.\n"; + + if (testPIN(pin1, pin1, NUM_DIGITS)) + cout << "SUCCESS: pin1 and pin1 report to be the same.\n"; + else + cout << "ERROR: pin1 and pin1 report to be different.\n"; + return 0; +} + +//****************************************************************** +// The following function accepts two int arrays. The arrays are * +// compared. If they contain the same values, true is returned. * +// If the contain different values, false is returned. * +//****************************************************************** + +bool testPIN(const int custPIN[], const int databasePIN[], int size) +{ + for (int index = 0; index < size; index++) + { + if (custPIN[index] != databasePIN[index]) + return false; // We've found two different values. + } + return true; // If we make it this far, the values are the same. +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-24.cpp b/SourceCode/Chapter 07/Pr7-24.cpp new file mode 100755 index 0000000..66461b9 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-24.cpp @@ -0,0 +1,38 @@ +// This program stores, in two vectors, the hours worked by 5 +// employees, and their hourly pay rates. +#include +#include +#include // Needed to define vectors +using namespace std; + +int main() +{ + const int NUM_EMPLOYEES = 5; // Number of employees + vector hours(NUM_EMPLOYEES); // A vector of integers + vector payRate(NUM_EMPLOYEES); // A vector of doubles + int index; // Loop counter + + // Input the data. + cout << "Enter the hours worked by " << NUM_EMPLOYEES; + cout << " employees and their hourly rates.\n"; + for (index = 0; index < NUM_EMPLOYEES; index++) + { + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> hours[index]; + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> payRate[index]; + } + + // Display each employee's gross pay. + cout << "\nHere is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < NUM_EMPLOYEES; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-25.cpp b/SourceCode/Chapter 07/Pr7-25.cpp new file mode 100755 index 0000000..d37bfba --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-25.cpp @@ -0,0 +1,16 @@ +// This program demonstrates the range-based for loop with a vector. +#include +#include + using namespace std; + +int main() +{ + // Define and initialize a vector. + vector numbers { 10, 20, 30, 40, 50 }; + + // Display the vector elements. + for (int val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-26.cpp b/SourceCode/Chapter 07/Pr7-26.cpp new file mode 100755 index 0000000..a6d5126 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-26.cpp @@ -0,0 +1,24 @@ +// This program demonstrates the range-based for loop with a vector. +#include +#include + using namespace std; + +int main() +{ + // Define and initialize a vector. + vector numbers(5); + + // Get values for the vector elements. + for (int &val : numbers) + { + cout << "Enter an integer value: "; + cin >> val; + } + + // Display the vector elements. + cout << "Here are the values that you entered:\n"; + for (int val : numbers) + cout << val << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-27.cpp b/SourceCode/Chapter 07/Pr7-27.cpp new file mode 100755 index 0000000..973a3a5 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-27.cpp @@ -0,0 +1,47 @@ +// This program stores, in two arrays, the hours worked by 5 +// employees, and their hourly pay rates. +#include +#include +#include // Needed to define vectors +using namespace std; + +int main() +{ + vector hours; // hours is an empty vector + vector payRate; // payRate is an empty vector + int numEmployees; // The number of employees + int index; // Loop counter + + // Get the number of employees. + cout << "How many employees do you have? "; + cin >> numEmployees; + + // Input the payroll data. + cout << "Enter the hours worked by " << numEmployees; + cout << " employees and their hourly rates.\n"; + for (index = 0; index < numEmployees; index++) + { + int tempHours; // To hold the number of hours entered + double tempRate; // To hold the payrate entered + + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> tempHours; + hours.push_back(tempHours); // Add an element to hours + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> tempRate; + payRate.push_back(tempRate); // Add an element to payRate + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < numEmployees; index++) + { + double grossPay = hours[index] * payRate[index]; + cout << "Employee #" << (index + 1); + cout << ": $" << grossPay << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-28.cpp b/SourceCode/Chapter 07/Pr7-28.cpp new file mode 100755 index 0000000..fb3b181 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-28.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the vector size +// member function. +#include +#include +using namespace std; + +// Function prototype +void showValues(vector); + +int main() +{ + vector values; + + // Put a series of numbers in the vector. + for (int count = 0; count < 7; count++) + values.push_back(count * 2); + + // Display the numbers. + showValues(values); + return 0; +} + +//************************************************** +// Definition of function showValues. * +// This function accepts an int vector as its * +// argument. The value of each of the vector's * +// elements is displayed. * +//************************************************** + +void showValues(vector vect) +{ + for (int count = 0; count < vect.size(); count++) + cout << vect[count] << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-29.cpp b/SourceCode/Chapter 07/Pr7-29.cpp new file mode 100755 index 0000000..882d03c --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-29.cpp @@ -0,0 +1,31 @@ +// This program demonstrates the vector pop_back member function. +#include +#include +using namespace std; + +int main() +{ + vector values; + + // Store values in the vector. + values.push_back(1); + values.push_back(2); + values.push_back(3); + cout << "The size of values is " << values.size() << endl; + + // Remove a value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + + // Now remove another value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + + // Remove the last value from the vector. + cout << "Popping a value from the vector...\n"; + values.pop_back(); + cout << "The size of values is now " << values.size() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-3.cpp b/SourceCode/Chapter 07/Pr7-3.cpp new file mode 100755 index 0000000..a0b7533 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-3.cpp @@ -0,0 +1,29 @@ +// This program reads data from a file into an array. +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 10; // Array size + int numbers[ARRAY_SIZE]; // Array with 10 elements + int count = 0; // Loop counter variable + ifstream inputFile; // Input file stream object + + // Open the file. + inputFile.open("TenNumbers.txt"); + + // Read the numbers from the file into the array. + while (count < ARRAY_SIZE && inputFile >> numbers[count]) + count++; + + // Close the file. + inputFile.close(); + + // Display the numbers read: + cout << "The numbers are: "; + for (count = 0; count < ARRAY_SIZE; count++) + cout << numbers[count] << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-30.cpp b/SourceCode/Chapter 07/Pr7-30.cpp new file mode 100755 index 0000000..1e9c2c9 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-30.cpp @@ -0,0 +1,17 @@ +// This program demonstrates the vector clear member function. +#include +#include +using namespace std; + +int main() +{ + vector values(100); + + cout << "The values vector has " + << values.size() << " elements.\n"; + cout << "I will call the clear member function...\n"; + values.clear(); + cout << "Now, the values vector has " + << values.size() << " elements.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-31.cpp b/SourceCode/Chapter 07/Pr7-31.cpp new file mode 100755 index 0000000..f556757 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-31.cpp @@ -0,0 +1,59 @@ +// This program demonstrates the vector's empty member function. +#include +#include +using namespace std; + +// Function prototype +double avgVector(vector); + +int main() +{ + vector values; // A vector to hold values + int numValues; // The number of values + double average; // To hold the average + + // Get the number of values to averge. + cout << "How many values do you wish to average? "; + cin >> numValues; + + // Get the values and store them in the vector. + for (int count = 0; count < numValues; count++) + { + int tempValue; + cout << "Enter a value: "; + cin >> tempValue; + values.push_back(tempValue); + } + + // Get the average of the values and display it. + average = avgVector(values); + cout << "Average: " << average << endl; + return 0; +} + +//************************************************************* +// Definition of function avgVector. * +// This function accepts an int vector as its argument. If * +// the vector contains values, the function returns the * +// average of those values. Otherwise, an error message is * +// displayed and the function returns 0.0. * +//************************************************************* + +double avgVector(vector vect) +{ + int total = 0; // accumulator + double avg; // average + + if (vect.empty()) // Determine if the vector is empty + { + cout << "No values to average.\n"; + avg = 0.0; + } + else + { + for (int count = 0; count < vect.size(); count++) + total += vect[count]; + avg = total / vect.size(); + } + return avg; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-4.cpp b/SourceCode/Chapter 07/Pr7-4.cpp new file mode 100755 index 0000000..6019e5a --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-4.cpp @@ -0,0 +1,30 @@ +// This program writes the contents of an array to a file. +#include +#include +using namespace std; + +int main() +{ + const int ARRAY_SIZE = 10; // Array size + int numbers[ARRAY_SIZE]; // Array with 10 elements + int count; // Loop counter variable + ofstream outputFile; // Output file stream object + + // Store values in the array. + for (count = 0; count < ARRAY_SIZE; count++) + numbers[count] = count; + + // Open a file for output. + outputFile.open("SavedNumbers.txt"); + + // Write the array contents to the file. + for (count = 0; count < ARRAY_SIZE; count++) + outputFile << numbers[count] << endl; + + // Close the file. + outputFile.close(); + + // That's it! + cout << "The numbers were saved to the file.\n "; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-5.cpp b/SourceCode/Chapter 07/Pr7-5.cpp new file mode 100755 index 0000000..9361353 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-5.cpp @@ -0,0 +1,24 @@ +// This program unsafely accesses an area of memory by writing +// values beyond an array's boundary. +// WARNING: If you compile and run this program, it could crash. +#include +using namespace std; + +int main() +{ + const int SIZE = 3; // Constant for the array size + int values[SIZE]; // An array of 3 integers + int count; // Loop counter variable + + // Attempt to store five numbers in the three-element array. + cout << "I will store 5 numbers in a 3 element array!\n"; + for (count = 0; count < 5; count++) + values[count] = 100; + + // If the program is still running, display the numbers. + cout << "If you see this message, it means the program\n"; + cout << "has not crashed! Here are the numbers:\n"; + for (count = 0; count < 5; count++) + cout << values[count] << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-6.cpp b/SourceCode/Chapter 07/Pr7-6.cpp new file mode 100755 index 0000000..f44a7f0 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-6.cpp @@ -0,0 +1,18 @@ +// This program displays the number of days in each month. +#include +using namespace std; + +int main() +{ + const int MONTHS = 12; + int days[MONTHS] = { 31, 28, 31, 30, + 31, 30, 31, 31, + 30, 31, 30, 31}; + + for (int count = 0; count < MONTHS; count++) + { + cout << "Month " << (count + 1) << " has "; + cout << days[count] << " days.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-7.cpp b/SourceCode/Chapter 07/Pr7-7.cpp new file mode 100755 index 0000000..70e2d8b --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-7.cpp @@ -0,0 +1,18 @@ +// This program initializes a string array. +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 9; + string planets[SIZE] = { "Mercury", "Venus", "Earth", "Mars", + "Jupiter", "Saturn", "Uranus", + "Neptune", "Pluto (a dwarf planet)" }; + + cout << "Here are the planets:\n"; + + for (int count = 0; count < SIZE; count++) + cout << planets[count] << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-8.cpp b/SourceCode/Chapter 07/Pr7-8.cpp new file mode 100755 index 0000000..00a77ef --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-8.cpp @@ -0,0 +1,21 @@ +// This program uses an array of ten characters to store the +// first ten Letters of the alphabet. The ASCII codes of the +// characters are displayed. +#include +using namespace std; + +int main() +{ + const int NUM_LETTERS = 10; + char letters[NUM_LETTERS] = {'A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J'}; + + cout << "Character" << "\t" << "ASCII Code\n"; + cout << "---------" << "\t" << "----------\n"; + for (int count = 0; count < NUM_LETTERS; count++) + { + cout << letters[count] << "\t\t"; + cout << static_cast(letters[count]) << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/Pr7-9.cpp b/SourceCode/Chapter 07/Pr7-9.cpp new file mode 100755 index 0000000..d6eed98 --- /dev/null +++ b/SourceCode/Chapter 07/Pr7-9.cpp @@ -0,0 +1,16 @@ +// This program has a partially initialized array. +#include +using namespace std; + +int main() +{ + const int SIZE = 7; + int numbers[SIZE] = {1, 2, 4, 8}; // Initialize first 4 elements + + cout << "Here are the contents of the array:\n"; + for (int index = 0; index < SIZE; index++) + cout << numbers[index] << " "; + + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 07/SavedNumbers.txt b/SourceCode/Chapter 07/SavedNumbers.txt new file mode 100755 index 0000000..127f666 --- /dev/null +++ b/SourceCode/Chapter 07/SavedNumbers.txt @@ -0,0 +1,10 @@ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 diff --git a/SourceCode/Chapter 07/TenNumbers.txt b/SourceCode/Chapter 07/TenNumbers.txt new file mode 100755 index 0000000..9a13b6b --- /dev/null +++ b/SourceCode/Chapter 07/TenNumbers.txt @@ -0,0 +1,10 @@ +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 diff --git a/SourceCode/Chapter 07/numbers.txt b/SourceCode/Chapter 07/numbers.txt new file mode 100755 index 0000000..7d2cdb3 --- /dev/null +++ b/SourceCode/Chapter 07/numbers.txt @@ -0,0 +1,12 @@ +47 +89 +65 +36 +12 +25 +17 +8 +62 +10 +87 +62 diff --git a/SourceCode/Chapter 08/Pr8-1.cpp b/SourceCode/Chapter 08/Pr8-1.cpp new file mode 100755 index 0000000..c7ccf93 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-1.cpp @@ -0,0 +1,55 @@ +// This program demonstrates the searchList function, which +// performs a linear search on an integer array. +#include +using namespace std; + +// Function prototype +int searchList(const int [], int, int); +const int SIZE = 5; + +int main() +{ + int tests[SIZE] = {87, 75, 98, 100, 82}; + int results; + + // Search the array for 100. + results = searchList(tests, SIZE, 100); + + // If searchList returned -1, then 100 was not found. + if (results == -1) + cout << "You did not earn 100 points on any test\n"; + else + { + // Otherwise results contains the subscript of + // the first 100 in the array. + cout << "You earned 100 points on test "; + cout << (results + 1) << endl; + } + return 0; +} + +//***************************************************************** +// The searchList function performs a linear search on an * +// integer array. The array list, which has a maximum of numElems * +// elements, is searched for the number stored in value. If the * +// number is found, its array subscript is returned. Otherwise, * +// -1 is returned indicating the value was not in the array. * +//***************************************************************** + +int searchList(const int list[], int numElems, int value) +{ + int index = 0; // Used as a subscript to search array + int position = -1; // To record position of search value + bool found = false; // Flag to indicate if the value was found + + while (index < numElems && !found) + { + if (list[index] == value) // If the value is found + { + found = true; // Set the flag + position = index; // Record the value's subscript + } + index++; // Go to the next element + } + return position; // Return the position, or -1 +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-2.cpp b/SourceCode/Chapter 08/Pr8-2.cpp new file mode 100755 index 0000000..cac29e6 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-2.cpp @@ -0,0 +1,69 @@ +// This program demonstrates the binarySearch function, which +// performs a binary search on an integer array. +#include +using namespace std; + +// Function prototype +int binarySearch(const int [], int, int); +const int SIZE = 20; + +int main() +{ + // Array with employee IDs sorted in ascending order. + int idNums[SIZE] = {101, 142, 147, 189, 199, 207, 222, + 234, 289, 296, 310, 319, 388, 394, + 417, 429, 447, 521, 536, 600}; + int results; // To hold the search results + int empID; // To hold an employee ID + + // Get an employee ID to search for. + cout << "Enter the employee ID you wish to search for: "; + cin >> empID; + + // Search for the ID. + results = binarySearch(idNums, SIZE, empID); + + // If results contains -1 the ID was not found. + if (results == -1) + cout << "That number does not exist in the array.\n"; + else + { + // Otherwise results contains the subscript of + // the specified employee ID in the array. + cout << "That ID is found at element " << results; + cout << " in the array.\n"; + } + return 0; +} + +//*************************************************************** +// The binarySearch function performs a binary search on an * +// integer array. array, which has a maximum of size elements, * +// is searched for the number stored in value. If the number is * +// found, its array subscript is returned. Otherwise, -1 is * +// returned indicating the value was not in the array. * +//*************************************************************** + +int binarySearch(const int array[], int size, int value) +{ + int first = 0, // First array element + last = size - 1, // Last array element + middle, // Mid point of search + position = -1; // Position of search value + bool found = false; // Flag + + while (!found && first <= last) + { + middle = (first + last) / 2; // Calculate mid point + if (array[middle] == value) // If value is found at mid + { + found = true; + position = middle; + } + else if (array[middle] > value) // If value is in lower half + last = middle - 1; + else + first = middle + 1; // If value is in upper half + } + return position; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-3.cpp b/SourceCode/Chapter 08/Pr8-3.cpp new file mode 100755 index 0000000..9491f08 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-3.cpp @@ -0,0 +1,143 @@ +// Demetris Leadership Center (DLC) product lookup program +// This program allows the user to enter a product number +// and then displays the title, description, and price of +// that product. +#include +#include +using namespace std; + +const int NUM_PRODS = 9; // The number of products produced +const int MIN_PRODNUM = 914; // The lowest product number +const int MAX_PRODNUM = 922; // The highest product number + +// Function prototypes +int getProdNum(); +int binarySearch (const int [], int, int); +void displayProd(const string [], const string [], const double [], int); + +int main() +{ + // Array of product IDs + int id[NUM_PRODS] = {914, 915, 916, 917, 918, 919, 920, + 921, 922}; + + // Array of product titles + string title[NUM_PRODS] = + { "Six Steps to Leadership", + "Six Steps to Leadership", + "The Road to Excellence", + "Seven Lessons of Quality", + "Seven Lessons of Quality", + "Seven Lessons of Quality", + "Teams Are Made, Not Born", + "Leadership for the Future", + "Leadership for the Future" + }; + + // Array of product descriptions + string description[NUM_PRODS] = + { "Book", "Audio CD", "DVD", + "Book", "Audio CD", "DVD", + "Book", "Book", "Audio CD" + }; + + // Array of product prices + double prices[NUM_PRODS] = {12.95, 14.95, 18.95, 16.95, 21.95, + 31.95, 14.95, 14.95, 16.95}; + + int prodNum; // To hold a product number + int index; // To hold search results + char again; // To hold a Y or N answer + + do + { + // Get the desired product number. + prodNum = getProdNum(); + + // Search for the product number. + index = binarySearch(id, NUM_PRODS, prodNum); + + // Display the results of the search. + if (index == -1) + cout << "That product number was not found.\n"; + else + displayProd(title, description, prices, index); + + // Does the user want to do this again? + cout << "Would you like to look up another product? (y/n) "; + cin >> again; + } while (again == 'y' || again == 'Y'); + return 0; +} + +//*************************************************** +// Definition of getProdNum function * +// The getProdNum function asks the user to enter a * +// product number. The input is validated, and when * +// a valid number is entered, it is returned. * +//*************************************************** + +int getProdNum() +{ + int prodNum; // Product number + + cout << "Enter the item's product number: "; + cin >> prodNum; + // Validate input + while (prodNum < MIN_PRODNUM || prodNum > MAX_PRODNUM) + { + cout << "Enter a number in the range of " << MIN_PRODNUM; + cout <<" through " << MAX_PRODNUM << ".\n"; + cin >> prodNum; + } + return prodNum; +} + +//*************************************************************** +// Definition of binarySearch function * +// The binarySearch function performs a binary search on an * +// integer array. array, which has a maximum of numElems * +// elements, is searched for the number stored in value. If the * +// number is found, its array subscript is returned. Otherwise, * +// -1 is returned indicating the value was not in the array. * +//*************************************************************** + +int binarySearch(const int array[], int numElems, int value) +{ + int first = 0, // First array element + last = numElems - 1, // Last array element + middle, // Midpoint of search + position = -1; // Position of search value + bool found = false; // Flag + + while (!found && first <= last) + { + middle = (first + last) / 2; // Calculate midpoint + if (array[middle] == value) // If value is found at mid + { + found = true; + position = middle; + } + else if (array[middle] > value) // If value is in lower half + last = middle - 1; + else + first = middle + 1; // If value is in upper half + } + return position; +} + +//************************************************************ +// The displayProd function accepts three arrays and an int. * +// The arrays parameters are expected to hold the title, * +// description, and prices arrays defined in main. The index * +// parameter holds a subscript. This function displays the * +// information in each array contained at the subscript. * +//************************************************************ + +void displayProd(const string title[], const string desc[], + const double price[], int index) +{ + cout << "Title: " << title[index] << endl; + cout << "Description: " << desc[index] << endl; + cout << "Price: $" << price[index] << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-4.cpp b/SourceCode/Chapter 08/Pr8-4.cpp new file mode 100755 index 0000000..9140c73 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-4.cpp @@ -0,0 +1,66 @@ +// This program uses the bubble sort algorithm to sort an +// array in ascending order. +#include +using namespace std; + +// Function prototypes +void sortArray(int [], int); +void showArray(const int [], int); + +int main() +{ + // Array of unsorted values + int values[6] = {7, 2, 3, 8, 9, 1}; + + // Display the values. + cout << "The unsorted values are:\n"; + showArray(values, 6); + + // Sort the values. + sortArray(values, 6); + + // Display them again. + cout << "The sorted values are:\n"; + showArray(values, 6); + return 0; +} + +//*********************************************************** +// Definition of function sortArray * +// This function performs an ascending order bubble sort on * +// array. size is the number of elements in the array. * +//*********************************************************** + +void sortArray(int array[], int size) +{ + bool swap; + int temp; + + do + { + swap = false; + for (int count = 0; count < (size - 1); count++) + { + if (array[count] > array[count + 1]) + { + temp = array[count]; + array[count] = array[count + 1]; + array[count + 1] = temp; + swap = true; + } + } + } while (swap); +} + +//************************************************************* +// Definition of function showArray. * +// This function displays the contents of array. size is the * +// number of elements. * +//************************************************************* + +void showArray(const int array[], int size) +{ + for (int count = 0; count < size; count++) + cout << array[count] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-5.cpp b/SourceCode/Chapter 08/Pr8-5.cpp new file mode 100755 index 0000000..4b586de --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-5.cpp @@ -0,0 +1,67 @@ +// This program uses the selection sort algorithm to sort an +// array in ascending order. +#include +using namespace std; + +// Function prototypes +void selectionSort(int [], int); +void showArray(int [], int); + +int main() +{ + // Define an array with unsorted values + const int SIZE = 6; + int values[SIZE] = {5, 7, 2, 8, 9, 1}; + + // Display the values. + cout << "The unsorted values are\n"; + showArray(values, SIZE); + + // Sort the values. + selectionSort(values, SIZE); + + // Display the values again. + cout << "The sorted values are\n"; + showArray(values, SIZE); + return 0; +} + +//************************************************************** +// Definition of function selectionSort. * +// This function performs an ascending order selection sort on * +// array. size is the number of elements in the array. * +//************************************************************** + +void selectionSort(int array[], int size) +{ + int startScan, minIndex, minValue; + + for (startScan = 0; startScan < (size - 1); startScan++) + { + minIndex = startScan; + minValue = array[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (array[index] < minValue) + { + minValue = array[index]; + minIndex = index; + } + } + array[minIndex] = array[startScan]; + array[startScan] = minValue; + } +} + +//************************************************************** +// Definition of function showArray. * +// This function displays the contents of array. size is the * +// number of elements. * +//************************************************************** + +void showArray(int array[], int size) +{ + for (int count = 0; count < size; count++) + cout << array[count] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-6.cpp b/SourceCode/Chapter 08/Pr8-6.cpp new file mode 100755 index 0000000..eb0fe03 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-6.cpp @@ -0,0 +1,139 @@ +// This program produces a sales report for DLC, Inc. +#include +#include +using namespace std; + +// Function prototypes +void calcSales(const int [], const double [], double [], int); +void showOrder(const double [], const int [], int); +void dualSort(int [], double [], int); +void showTotals(const double [], const int [], int); + +// NUM_PRODS is the number of products produced. +const int NUM_PRODS = 9; + +int main() +{ + // Array with product ID numbers + int id[NUM_PRODS] = {914, 915, 916, 917, 918, 919, 920, + 921, 922}; + + // Array with number of units sold for each product + int units[NUM_PRODS] = {842, 416, 127, 514, 437, 269, 97, + 492, 212}; + + // Array with product prices + double prices[NUM_PRODS] = {12.95, 14.95, 18.95, 16.95, 21.95, + 31.95, 14.95, 14.95, 16.95}; + + // Array to hold the computed sales amounts + double sales[NUM_PRODS]; + + // Calculate each product's sales. + calcSales(units, prices, sales, NUM_PRODS); + + // Sort the elements in the sales array in descending + // order and shuffle the ID numbers in the id array to + // keep them in parallel. + dualSort(id, sales, NUM_PRODS); + + // Set the numeric output formatting. + cout << setprecision(2) << fixed << showpoint; + + // Display the products and sales amounts. + showOrder(sales, id, NUM_PRODS); + + // Display total units sold and total sales. + showTotals(sales, units, NUM_PRODS); + return 0; +} + +//**************************************************************** +// Definition of calcSales. Accepts units, prices, and sales * +// arrays as arguments. The size of these arrays is passed * +// into the num parameter. This function calculates each * +// product's sales by multiplying its units sold by each unit's * +// price. The result is stored in the sales array. * +//**************************************************************** + +void calcSales(const int units[], const double prices[], double sales[], int num) +{ + for (int index = 0; index < num; index++) + sales[index] = units[index] * prices[index]; +} + +//*************************************************************** +// Definition of function dualSort. Accepts id and sales arrays * +// as arguments. The size of these arrays is passed into size. * +// This function performs a descending order selection sort on * +// the sales array. The elements of the id array are exchanged * +// identically as those of the sales array. size is the number * +// of elements in each array. * +//*************************************************************** + +void dualSort(int id[], double sales[], int size) +{ + int startScan, maxIndex, tempid; + double maxValue; + + for (startScan = 0; startScan < (size - 1); startScan++) + { + maxIndex = startScan; + maxValue = sales[startScan]; + tempid = id[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (sales[index] > maxValue) + { + maxValue = sales[index]; + tempid = id[index]; + maxIndex = index; + } + } + sales[maxIndex] = sales[startScan]; + id[maxIndex] = id[startScan]; + sales[startScan] = maxValue; + id[startScan] = tempid; + } +} + +//**************************************************************** +// Definition of showOrder function. Accepts sales and id arrays * +// as arguments. The size of these arrays is passed into num. * +// The function first displays a heading, then the sorted list * +// of product numbers and sales. * +//**************************************************************** + +void showOrder(const double sales[], const int id[], int num) +{ + cout << "Product Number\tSales\n"; + cout << "----------------------------------\n"; + for (int index = 0; index < num; index++) + { + cout << id[index] << "\t\t$"; + cout << setw(8) << sales[index] << endl; + } + cout << endl; +} + +//***************************************************************** +// Definition of showTotals function. Accepts sales and id arrays * +// as arguments. The size of these arrays is passed into num. * +// The function first calculates the total units (of all * +// products) sold and the total sales. It then displays these * +// amounts. * +//***************************************************************** + +void showTotals(const double sales[], const int units[], int num) +{ + int totalUnits = 0; + double totalSales = 0.0; + + for (int index = 0; index < num; index++) + { + totalUnits += units[index]; + totalSales += sales[index]; + } + cout << "Total units Sold: " << totalUnits << endl; + cout << "Total sales: $" << totalSales << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-7.cpp b/SourceCode/Chapter 08/Pr8-7.cpp new file mode 100755 index 0000000..0952815 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-7.cpp @@ -0,0 +1,169 @@ +// This program produces a sales report for DLC, Inc. +// This version of the program uses STL vectors instead of arrays. +#include +#include +#include +using namespace std; + +// Function prototypes +void initVectors(vector &, vector &, vector &); +void calcSales(vector, vector, vector &); +void showOrder(vector, vector); +void dualSort(vector &, vector &); +void showTotals(vector, vector); + +int main() +{ + vector id; // Product ID numbers + vector units; // Units sold + vector prices; // Product prices + vector sales; // To hold product sales + + // Must provide an initialization routine. + initVectors(id, units, prices); + + // Calculate each product's sales. + calcSales(units, prices, sales); + + // Sort the elements in the sales array in descending + // order and shuffle the ID numbers in the id array to + // keep them in parallel. + dualSort(id, sales); + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the products and sales amounts. + showOrder(sales, id); + + // Display total units sold and total sales. + showTotals(sales, units); + return 0; +} + +//****************************************************************** +// Definition of initVectors. Accepts id, units, and prices * +// vectors as reference arguments. This function initializes each * +// vector to a set of starting values. * +//****************************************************************** + +void initVectors(vector &id, vector &units, + vector &prices) +{ + // Initialize the id vector with the ID numbers + // 914 through 922. + for (int value = 914; value <= 922; value++) + id.push_back(value); + + // Initialize the units vector with data. + units.push_back(842); + units.push_back(416); + units.push_back(127); + units.push_back(514); + units.push_back(437); + units.push_back(269); + units.push_back(97); + units.push_back(492); + units.push_back(212); + + // Initialize the prices vector. + prices.push_back(12.95); + prices.push_back(14.95); + prices.push_back(18.95); + prices.push_back(16.95); + prices.push_back(21.95); + prices.push_back(31.95); + prices.push_back(14.95); + prices.push_back(14.95); + prices.push_back(16.95); +} + + +//**************************************************************** +// Definition of calcSales. Accepts units, prices, and sales * +// vectors as arguments. The sales vector is passed into a * +// reference parameter. This function calculates each product's * +// sales by multiplying its units sold by each unit's price. The * +// result is stored in the sales vector. * +//**************************************************************** + +void calcSales(vector units, vector prices, + vector &sales) +{ + for (int index = 0; index < units.size(); index++) + sales.push_back(units[index] * prices[index]); +} + +//**************************************************************** +// Definition of function dualSort. Accepts id and sales vectors * +// as reference arguments. This function performs a descending * +// order selection sort on the sales vector. The elements of the * +// id vector are exchanged identically as those of the sales * +// vector. * +//**************************************************************** + +void dualSort(vector &id, vector &sales) +{ + int startScan, maxIndex, tempid, size; + double maxValue; + + size = id.size(); + for (startScan = 0; startScan < (size - 1); startScan++) + { + maxIndex = startScan; + maxValue = sales[startScan]; + tempid = id[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (sales[index] > maxValue) + { + maxValue = sales[index]; + tempid = id[index]; + maxIndex = index; + } + } + sales[maxIndex] = sales[startScan]; + id[maxIndex] = id[startScan]; + sales[startScan] = maxValue; + id[startScan] = tempid; + } +} + +//***************************************************************** +// Definition of showOrder function. Accepts sales and id vectors * +// as arguments. The function first displays a heading, then the * +// sorted list of product numbers and sales. * +//***************************************************************** + +void showOrder(vector sales, vector id) +{ + cout << "Product Number\tSales\n"; + cout << "----------------------------------\n"; + for (int index = 0; index < id.size(); index++) + { + cout << id[index] << "\t\t$"; + cout << setw(8) << sales[index] << endl; + } + cout << endl; +} + +//******************************************************************* +// Definition of showTotals function. Accepts sales and id vectors * +// as arguments. The function first calculates the total units (of * +// all products) sold and the total sales. It then displays these * +// amounts. * +//******************************************************************* + +void showTotals(vector sales, vector units) +{ + int totalUnits = 0; + double totalSales = 0.0; + + for (int index = 0; index < units.size(); index++) + { + totalUnits += units[index]; + totalSales += sales[index]; + } + cout << "Total Units Sold: " << totalUnits << endl; + cout << "Total Sales: $" << totalSales << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 08/Pr8-8.cpp b/SourceCode/Chapter 08/Pr8-8.cpp new file mode 100755 index 0000000..6092192 --- /dev/null +++ b/SourceCode/Chapter 08/Pr8-8.cpp @@ -0,0 +1,19 @@ +#include +#include +using namespace std; + +int main() +{ + const int NUM_NAMES = 20; + string names[NUM_NAMES] = {"Collins, Bill", "Smith, Bart", "Allen, Jim", + "Griffin, Jim", "Stamey, Marty", "Rose, Geri", + "Taylor, Terri", "Johnson, Jill", "Allison, Jeff", + "Looney, Joe", "Wolfe, Bill", "James, Jean", + "Weaver, Jim", "Pore, Bob", "Rutherford, Greg", + "Javens, Renee", "Harrison, Rose", "Setzer, Cathy", + "Pike, Gordon", "Holland, Beth" }; + + // Insert your code to complete this program + + return 0; +} diff --git a/SourceCode/Chapter 09/Pr9-1.cpp b/SourceCode/Chapter 09/Pr9-1.cpp new file mode 100755 index 0000000..500c1a1 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-1.cpp @@ -0,0 +1,14 @@ +// This program uses the & operator to determine a variable’s +// address and the sizeof operator to determine its size. +#include +using namespace std; + +int main() +{ + int x = 25; + + cout << "The address of x is " << &x << endl; + cout << "The size of x is " << sizeof(x) << " bytes\n"; + cout << "The value in x is " << x << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-10.cpp b/SourceCode/Chapter 09/Pr9-10.cpp new file mode 100755 index 0000000..c98beb6 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-10.cpp @@ -0,0 +1,33 @@ +// This program uses a pointer to display the contents +// of an integer array. +#include +using namespace std; + +int main() +{ + int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; + int *nums = set; // Make nums point to set + + // Display the numbers in the array. + cout << "The numbers in set are:\n"; + cout << *nums << " "; // Display first element + while (nums < &set[7]) + { + // Advance nums to point to the next element. + nums++; + // Display the value pointed to by nums. + cout << *nums << " "; + } + + // Display the numbers in reverse order. + cout << "\nThe numbers in set backward are:\n"; + cout << *nums << " "; // Display first element + while (nums > set) + { + // Move backward to the previous element. + nums--; + // Display the value pointed to by nums. + cout << *nums << " "; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-11.cpp b/SourceCode/Chapter 09/Pr9-11.cpp new file mode 100755 index 0000000..f11fa6e --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-11.cpp @@ -0,0 +1,46 @@ +// This program uses two functions that accept addresses of +// variables as arguments. +#include +using namespace std; + +// Function prototypes +void getNumber(int *); +void doubleValue(int *); + +int main() +{ + int number; + + // Call getNumber and pass the address of number. + getNumber(&number); + + // Call doubleValue and pass the address of number. + doubleValue(&number); + + // Display the value in number. + cout << "That value doubled is " << number << endl; + return 0; +} + +//*************************************************************** +// Definition of getNumber. The parameter, input, is a pointer. * +// This function asks the user for a number. The value entered * +// is stored in the variable pointed to by input. * +//*************************************************************** + +void getNumber(int *input) +{ + cout << "Enter an integer number: "; + cin >> *input; +} + +//*************************************************************** +// Definition of doubleValue. The parameter, val, is a pointer. * +// This function multiplies the variable pointed to by val by * +// two. * +//*************************************************************** + +void doubleValue(int *val) +{ + *val *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-12.cpp b/SourceCode/Chapter 09/Pr9-12.cpp new file mode 100755 index 0000000..6e98eb6 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-12.cpp @@ -0,0 +1,58 @@ +// This program demonstrates that a pointer may be used as a +// parameter to accept the address of an array. +#include +#include +using namespace std; + +// Function prototypes +void getSales(double *, int); +double totalSales(double *, int); + +int main() +{ + const int QTRS = 4; + double sales[QTRS]; + + // Get the sales data for all quarters. + getSales(sales, QTRS); + + // Set the numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the total sales for the year. + cout << "The total sales for the year are $"; + cout << totalSales(sales, QTRS) << endl; + return 0; +} + +//***************************************************************** +// Definition of getSales. This function uses a pointer to accept * +// the address of an array of doubles. The function asks the user * +// user to enter sales figures and stores them in the array. * +//***************************************************************** +void getSales(double *arr, int size) +{ + for (int count = 0; count < size; count++) + { + cout << "Enter the sales figure for quarter "; + cout << (count + 1) << ": "; + cin >> arr[count]; + } +} + +//***************************************************************** +// Definition of totalSales. This function uses a pointer to * +// accept the address of an array. The function returns the total * +// of the elements in the array. * +//***************************************************************** +double totalSales(double *arr, int size) +{ + double sum = 0.0; + + for (int count = 0; count < size; count++) + { + sum += *arr; + arr++; + } + return sum; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-13.cpp b/SourceCode/Chapter 09/Pr9-13.cpp new file mode 100755 index 0000000..a065302 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-13.cpp @@ -0,0 +1,39 @@ +// This program demonstrates a pointer to const parameter +#include +using namespace std; + +void displayValues(const int *, int); + +int main() +{ + // Array sizes + const int SIZE = 6; + + // Define an array of const ints. + const int array1[SIZE] = { 1, 2, 3, 4, 5, 6 }; + + // Define an array of non-const ints. + int array2[SIZE] = { 2, 4, 6, 8, 10, 12 }; + + // Display the contents of the const array. + displayValues(array1, SIZE); + + // Display the contents of the non-const array. + displayValues(array2, SIZE); + return 0; +} + +//*************************************************** +// The displayValues function uses a pointer to * +// parameter to display the contents of an array. * +//*************************************************** + +void displayValues(const int *numbers, int size) +{ + // Display all the values. + for (int count = 0; count < size; count++) + { + cout << *(numbers + count) << " "; + } + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-14.cpp b/SourceCode/Chapter 09/Pr9-14.cpp new file mode 100755 index 0000000..7508414 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-14.cpp @@ -0,0 +1,52 @@ +// This program totals and averages the sales figures for any +// number of days. The figures are stored in a dynamically +// allocated array. +#include +#include +using namespace std; + +int main() +{ + double *sales = nullptr, // To dynamically allocate an array + total = 0.0, // Accumulator + average; // To hold average sales + int numDays, // To hold the number of days of sales + count; // Counter variable + + // Get the number of days of sales. + cout << "How many days of sales figures do you wish "; + cout << "to process? "; + cin >> numDays; + + // Dynamically allocate an array large enough to hold + // that many days of sales amounts. + sales = new double[numDays]; + + // Get the sales figures for each day. + cout << "Enter the sales figures below.\n"; + for (count = 0; count < numDays; count++) + { + cout << "Day " << (count + 1) << ": "; + cin >> sales[count]; + } + + // Calculate the total sales + for (count = 0; count < numDays; count++) + { + total += sales[count]; + } + + // Calculate the average sales per day + average = total / numDays; + + // Display the results + cout << fixed << showpoint << setprecision(2); + cout << "\n\nTotal Sales: $" << total << endl; + cout << "Average Sales: $" << average << endl; + + // Free dynamically allocated memory + delete [] sales; + sales = nullptr; // Make sales a nullptr. + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-15.cpp b/SourceCode/Chapter 09/Pr9-15.cpp new file mode 100755 index 0000000..0fb770a --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-15.cpp @@ -0,0 +1,55 @@ +// This program demonstrates a function that returns +// a pointer. +#include +#include // For rand and srand +#include // For the time function +using namespace std; + +// Function prototype +int *getRandomNumbers(int); + +int main() +{ + int *numbers; // To point to the numbers + + // Get an array of five random numbers. + numbers = getRandomNumbers(5); + + // Display the numbers. + for (int count = 0; count < 5; count++) + cout << numbers[count] << endl; + + // Free the memory. + delete [] numbers; + numbers = 0; + return 0; +} + +//************************************************** +// The getRandomNumbers function returns a pointer * +// to an array of random integers. The parameter * +// indicates the number of numbers requested. * +//************************************************** + +int *getRandomNumbers(int num) +{ + int *arr = nullptr; // Array to hold the numbers + + // Return null if num is zero or negative. + if (num <= 0) + return NULL; + + // Dynamically allocate the array. + arr = new int[num]; + + // Seed the random number generator by passing + // the return value of time(0) to srand. + srand( time(0) ); + + // Populate the array with random numbers. + for (int count = 0; count < num; count++) + arr[count] = rand(); + + // Return a pointer to the array. + return arr; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-16.cpp b/SourceCode/Chapter 09/Pr9-16.cpp new file mode 100755 index 0000000..4b514c9 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-16.cpp @@ -0,0 +1,91 @@ +// This program uses a function to duplicate +// an int array of any size. +#include +using namespace std; + +// Function prototype +int *duplicateArray(const int *, int); +void displayArray(const int[], int); + +int main() +{ + // Define constants for the array sizes. + const int SIZE1 = 5, SIZE2 = 7, SIZE3 = 10; + + // Define three arrays of different sizes. + int array1[SIZE1] = { 100, 200, 300, 400, 500 }; + int array2[SIZE2] = { 10, 20, 30, 40, 50, 60, 70 }; + int array3[SIZE3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + + // Define three pointers for the duplicate arrays. + int *dup1 = nullptr, *dup2 = nullptr, *dup3 = nullptr; + + // Duplicate the arrays. + dup1 = duplicateArray(array1, SIZE1); + dup2 = duplicateArray(array2, SIZE2); + dup3 = duplicateArray(array3, SIZE3); + + // Display the original arrays. + cout << "Here are the original array contents:\n"; + displayArray(array1, SIZE1); + displayArray(array2, SIZE2); + displayArray(array3, SIZE3); + + // Display the new arrays. + cout << "\nHere are the duplicate arrays:\n"; + displayArray(dup1, SIZE1); + displayArray(dup2, SIZE2); + displayArray(dup3, SIZE3); + + // Free the dynamically allocated memory and + // set the pointers to 0. + delete [] dup1; + delete [] dup2; + delete [] dup3; + dup1 = nullptr; + dup2 = nullptr; + dup3 = nullptr; + return 0; +} +//***************************************************** +// The duplicateArray function accepts an int array * +// and an int that indicates the array's size. The * +// function creates a new array that is a duplicate * +// of the argument array and returns a pointer to the * +// new array. If an invalid size is passed the * +// function returns null. * +//***************************************************** + +int *duplicateArray(const int *arr, int size) +{ + int *newArray = nullptr; + + // Validate the size. If 0 or a negative + // number was passed, return a null pointer. + if (size <= 0) + return nullptr; + + // Allocate a new array. + newArray = new int[size]; + + // Copy the array's contents to the + // new array. + for (int index = 0; index < size; index++) + newArray[index] = arr[index]; + + // Return a pointer to the new array. + return newArray; +} + +//************************************************** +// The displayArray function accepts an int array * +// and its size as arguments and displays the * +// contents of the array. * +//************************************************** + +void displayArray(const int arr[], int size) +{ + for (int index = 0; index < size; index++) + cout << arr[index] << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-17.cpp b/SourceCode/Chapter 09/Pr9-17.cpp new file mode 100755 index 0000000..8e71e3d --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-17.cpp @@ -0,0 +1,18 @@ +// This program demonstrates a unique_ptr. +#include +#include +using namespace std; + +int main() +{ + // Define a unique_ptr smart pointer, pointing + // to a dynamically allocated int. + unique_ptr ptr( new int ); + + // Assign 99 to the dynamically allocated int. + *ptr = 99; + + // Display the value of the dynamically allocated int. + cout << *ptr << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-18.cpp b/SourceCode/Chapter 09/Pr9-18.cpp new file mode 100755 index 0000000..61f9fe1 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-18.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a unique_ptr pointing +// to a dynamically allocated array of integers. +#include +#include +using namespace std; + +int main() +{ + int max; // Max size of the array + + // Get the number of values to store. + cout << "How many numbers do you want to enter? "; + cin >> max; + + // Define a unique_ptr smart pointer, pointing + // to a dynamically allocated array of ints. + unique_ptr ptr( new int[max]); + + // Get values for the array. + for (int index = 0; index < max; index++) + { + cout << "Enter an integer number: "; + cin >> ptr[index]; + } + + // Display the values in the array. + cout << "Here are the values you entered:\n"; + for (int index = 0; index < max; index++) + cout << ptr[index] << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-19.cpp b/SourceCode/Chapter 09/Pr9-19.cpp new file mode 100755 index 0000000..2e8f0f1 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-19.cpp @@ -0,0 +1,101 @@ +// This program shows the donations made to the United Cause +// by the employees of CK Graphics, Inc. It displays +// the donations in order from lowest to highest +// and in the original order they were received. +#include +using namespace std; + +// Function prototypes +void arrSelectSort(int *[], int); +void showArray(const int [], int); +void showArrPtr(int *[], int); + +int main() +{ + const int NUM_DONATIONS = 15; // Number of donations + + // An array containing the donation amounts. + int donations[NUM_DONATIONS] = { 5, 100, 5, 25, 10, + 5, 25, 5, 5, 100, + 10, 15, 10, 5, 10 }; + + // An array of pointers to int. + int *arrPtr[NUM_DONATIONS] = { nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr }; + + // Each element of arrPtr is a pointer to int. Make each + // element point to an element in the donations array. + for (int count = 0; count < NUM_DONATIONS; count++) + arrPtr[count] = &donations[count]; + + // Sort the elements of the array of pointers. + arrSelectSort(arrPtr, NUM_DONATIONS); + + // Display the donations using the array of pointers. This + // will display them in sorted order. + cout << "The donations, sorted in ascending order are: \n"; + showArrPtr(arrPtr, NUM_DONATIONS); + + // Display the donations in their original order. + cout << "The donations, in their original order are: \n"; + showArray(donations, NUM_DONATIONS); + return 0; +} + +//**************************************************************** +// Definition of function arrSelectSort. * +// This function performs an ascending order selection sort on * +// arr, which is an array of pointers. Each element of array * +// points to an element of a second array. After the sort, * +// arr will point to the elements of the second array in * +// ascending order. * +//**************************************************************** + +void arrSelectSort(int *arr[], int size) +{ + int startScan, minIndex; + int *minElem; + + for (startScan = 0; startScan < (size - 1); startScan++) + { + minIndex = startScan; + minElem = arr[startScan]; + for(int index = startScan + 1; index < size; index++) + { + if (*(arr[index]) < *minElem) + { + minElem = arr[index]; + minIndex = index; + } + } + arr[minIndex] = arr[startScan]; + arr[startScan] = minElem; + } +} + +//************************************************************* +// Definition of function showArray. * +// This function displays the contents of arr. size is the * +// number of elements. * +//************************************************************* + +void showArray(const int arr[], int size) +{ + for (int count = 0; count < size; count++) + cout << arr[count] << " "; + cout << endl; +} + +//************************************************************** +// Definition of function showArrPtr. * +// This function displays the contents of the array pointed to * +// by arr. size is the number of elements. * +//************************************************************** + +void showArrPtr(int *arr[], int size) +{ + for (int count = 0; count < size; count++) + cout << *(arr[count]) << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-2.cpp b/SourceCode/Chapter 09/Pr9-2.cpp new file mode 100755 index 0000000..91e655f --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-2.cpp @@ -0,0 +1,14 @@ +// This program stores the address of a variable in a pointer. +#include +using namespace std; + +int main() +{ + int x = 25; // int variable + int *ptr = nullptr; // Pointer variable, can point to an int + + ptr = &x; // Store the address of x in ptr + cout << "The value in x is " << x << endl; + cout << "The address of x is " << ptr << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-3.cpp b/SourceCode/Chapter 09/Pr9-3.cpp new file mode 100755 index 0000000..6d31292 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-3.cpp @@ -0,0 +1,26 @@ +// This program demonstrates the use of the indirection operator. +#include +using namespace std; + +int main() +{ + int x = 25; // int variable + int *ptr = nullptr; // Pointer variable, can point to an int + + ptr = &x; // Store the address of x in ptr + + // Use both x and ptr to display the value in x. + cout << "Here is the value in x, printed twice:\n"; + cout << x << endl; // Displays the contents of x + cout << *ptr << endl; // Displays the contents of x + + // Assign 100 to the location pointed to by ptr. This + // will actually assign 100 to x. + *ptr = 100; + + // Use both x and ptr to display the value in x. + cout << "Once again, here is the value in x:\n"; + cout << x << endl; // Displays the contents of x + cout << *ptr << endl; // Displays the contents of x + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-4.cpp b/SourceCode/Chapter 09/Pr9-4.cpp new file mode 100755 index 0000000..b470542 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-4.cpp @@ -0,0 +1,30 @@ +// This program demonstrates a pointer variable referencing +// different variables. +#include +using namespace std; + +int main() +{ + int x = 25, y = 50, z = 75; // Three int variables + int *ptr = nullptr; // Pointer variable + + // Display the contents of x, y, and z. + cout << "Here are the values of x, y, and z:\n"; + cout << x << " " << y << " " << z << endl; + + // Use the pointer to manipulate x, y, and z. + + ptr = &x; // Store the address of x in ptr. + *ptr += 100; // Add 100 to the value in x. + + ptr = &y; // Store the address of y in ptr. + *ptr += 100; // Add 100 to the value in y. + + ptr = &z; // Store the address of z in ptr. + *ptr += 100; // Add 100 to the value in z. + + // Display the contents of x, y, and z. + cout << "Once again, here are the values of x, y, and z:\n"; + cout << x << " " << y << " " << z << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-5.cpp b/SourceCode/Chapter 09/Pr9-5.cpp new file mode 100755 index 0000000..f2acc06 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-5.cpp @@ -0,0 +1,13 @@ +// This program shows an array name being dereferenced with the * +// operator. +#include +using namespace std; + +int main() +{ + short numbers[] = {10, 20, 30, 40, 50}; + + cout << "The first element of the array is "; + cout << *numbers << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-6.cpp b/SourceCode/Chapter 09/Pr9-6.cpp new file mode 100755 index 0000000..77670d4 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-6.cpp @@ -0,0 +1,24 @@ +// This program processes an array using pointer notation. +#include +using namespace std; + +int main() +{ + const int SIZE = 5; // Size of the array + int numbers[SIZE]; // Array of integers + int count; // Counter variable + + // Get values to store in the array. + // Use pointer notation instead of subscripts. + cout << "Enter " << SIZE << " numbers: "; + for (count = 0; count < SIZE; count++) + cin >> *(numbers + count); + + // Display the values in the array. + // Use pointer notation instead of subscripts. + cout << "Here are the numbers you entered:\n"; + for (count = 0; count < SIZE; count++) + cout << *(numbers + count)<< " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-7.cpp b/SourceCode/Chapter 09/Pr9-7.cpp new file mode 100755 index 0000000..77ed0ae --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-7.cpp @@ -0,0 +1,30 @@ +// This program uses subscript notation with a pointer variable and +// pointer notation with an array name. +#include +#include +using namespace std; + +int main() +{ + const int NUM_COINS = 5; + double coins[NUM_COINS] = {0.05, 0.1, 0.25, 0.5, 1.0}; + double *doublePtr; // Pointer to a double + int count; // Array index + + // Assign the address of the coins array to doublePtr. + doublePtr = coins; + + // Display the contents of the coins array. Use subscripts + // with the pointer! + cout << "Here are the values in the coins array:\n"; + for (count = 0; count < NUM_COINS; count++) + cout << doublePtr[count] << " "; + + // Display the contents of the array again, but this time + // use pointer notation with the array name! + cout << "\nAnd here they are again:\n"; + for (count = 0; count < NUM_COINS; count++) + cout << *(coins + count) << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-8.cpp b/SourceCode/Chapter 09/Pr9-8.cpp new file mode 100755 index 0000000..1f64108 --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-8.cpp @@ -0,0 +1,25 @@ +// This program uses the address of each element in the array. +#include +#include +using namespace std; + +int main() +{ + const int NUM_COINS = 5; + double coins[NUM_COINS] = {0.05, 0.1, 0.25, 0.5, 1.0}; + double *doublePtr = nullptr; // Pointer to a double + int count; // Array index + + // Use the pointer to display the values in the array. + cout << "Here are the values in the coins array:\n"; + for (count = 0; count < NUM_COINS; count++) + { + // Get the address of an array element. + doublePtr = &coins[count]; + + // Display the contents of the element. + cout << *doublePtr << " "; + } + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 09/Pr9-9.cpp b/SourceCode/Chapter 09/Pr9-9.cpp new file mode 100755 index 0000000..678230d --- /dev/null +++ b/SourceCode/Chapter 09/Pr9-9.cpp @@ -0,0 +1,31 @@ +// This program uses a pointer to display the contents of an array. +#include +using namespace std; + +int main() +{ + const int SIZE = 8; + int set[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; + int *numPtr = nullptr; // Pointer + int count; // Counter variable for loops + + // Make numPtr point to the set array. + numPtr = set; + + // Use the pointer to display the array contents. + cout << "The numbers in set are:\n"; + for (count = 0; count < SIZE; count++) + { + cout << *numPtr << " "; + numPtr++; + } + + // Display the array contents in reverse order. + cout << "\nThe numbers in set backward are:\n"; + for (count = 0; count < SIZE; count++) + { + numPtr--; + cout << *numPtr << " "; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-1.cpp b/SourceCode/Chapter 10/Pr10-1.cpp new file mode 100755 index 0000000..b3fc758 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-1.cpp @@ -0,0 +1,24 @@ +// This program demonstrates some character testing functions. +#include +#include +using namespace std; + +int main() +{ + char input; + + cout << "Enter any character: "; + cin.get(input); + cout << "The character you entered is: " << input << endl; + if (isalpha(input)) + cout << "That's an alphabetic character.\n"; + if (isdigit(input)) + cout << "That's a numeric digit.\n"; + if (islower(input)) + cout << "The letter you entered is lowercase.\n"; + if (isupper(input)) + cout << "The letter you entered is uppercase.\n"; + if (isspace(input)) + cout << "That's a whitespace character.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-10.cpp b/SourceCode/Chapter 10/Pr10-10.cpp new file mode 100755 index 0000000..c61d1bc --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-10.cpp @@ -0,0 +1,38 @@ +// This program demonstrates the strcmp and atoi functions. +#include +#include // For tolower +#include // For strcmp +#include // For atoi +using namespace std; + +int main() +{ + const int SIZE = 20; // Array size + char input[SIZE]; // To hold user input + int total = 0; // Accumulator + int count = 0; // Loop counter + double average; // To hold the average of numbers + + // Get the first number. + cout << "This program will average a series of numbers.\n"; + cout << "Enter the first number or Q to quit: "; + cin.getline(input, SIZE); + + // Process the number and subsequent numbers. + while (tolower(input[0]) != 'q') + { + total += atoi(input); // Keep a running total + count++; // Count the numbers entered + // Get the next number. + cout << "Enter the next number or Q to quit: "; + cin.getline(input, SIZE); + } + + // If any numbers were entered, display their average. + if (count != 0) + { + average = static_cast(total) / count; + cout << "Average: " << average << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-11.cpp b/SourceCode/Chapter 10/Pr10-11.cpp new file mode 100755 index 0000000..6ddac50 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-11.cpp @@ -0,0 +1,45 @@ +// This program demonstrates how the getline function can +// be used for all of a program's input. +#include +#include +#include +using namespace std; + +int main() +{ + const int INPUT_SIZE = 81; // Size of input array + const int NAME_SIZE = 30; // Size of name array + char input[INPUT_SIZE]; // To hold a line of input + char name[NAME_SIZE]; // To hold a name + int idNumber; // To hold an ID number. + int age; // To hold an age + double income; // To hold income + + // Get the user's ID number. + cout << "What is your ID number? "; + cin.getline(input, INPUT_SIZE); // Read as a string + idNumber = atoi(input); // Convert to int + + // Get the user's name. No conversion necessary. + cout << "What is your name? "; + cin.getline(name, NAME_SIZE); + + // Get the user's age. + cout << "How old are you? "; + cin.getline(input, INPUT_SIZE); // Read as a string + age = atoi(input); // Convert to int + + // Get the user's income. + cout << "What is your annual income? "; + cin.getline(input, INPUT_SIZE); // Read as a string + income = atof(input); // Convert to double + + // Show the resulting data. + cout << setprecision(2) << fixed << showpoint; + cout << "Your name is " << name + <<", you are " << age + << " years old,\nand you make $" + << income << " per year.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-12.cpp b/SourceCode/Chapter 10/Pr10-12.cpp new file mode 100755 index 0000000..d3849b3 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-12.cpp @@ -0,0 +1,45 @@ +// This program uses a function to copy a C-string into an array. +#include +using namespace std; + +void stringCopy(char [], char []); // Function prototype + +int main() +{ + const int LENGTH = 30; // Size of the arrays + char first[LENGTH]; // To hold the user's input + char second[LENGTH]; // To hold the copy + + // Get a string from the user and store in first. + cout << "Enter a string with no more than " + << (LENGTH - 1) << " characters:\n"; + cin.getline(first, LENGTH); + + // Copy the contents of first to second. + stringCopy(first, second); + + // Display the copy. + cout << "The string you entered is:\n" << second << endl; + return 0; +} + +//*********************************************************** +// Definition of the stringCopy function. * +// This function copies the C-string in string1 to string2. * +//*********************************************************** + +void stringCopy(char string1[], char string2[]) +{ + int index = 0; // Loop counter + + // Step through string1, copying each element to + // string2. Stop when the null character is encountered. + while (string1[index] != '\0') + { + string2[index] = string1[index]; + index++; + } + + // Place a null character in string2. + string2[index] = '\0'; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-13.cpp b/SourceCode/Chapter 10/Pr10-13.cpp new file mode 100755 index 0000000..8037f3a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-13.cpp @@ -0,0 +1,41 @@ +// This program uses the function nameSlice to cut the last +// name off of a string that contains the user's first and +// last names. +#include +using namespace std; + +void nameSlice(char []); // Function prototype + +int main() +{ + const int SIZE = 41; // Array size + char name[SIZE]; // To hold the user's name + + cout << "Enter your first and last names, separated "; + cout << "by a space:\n"; + cin.getline(name, SIZE); + nameSlice(name); + cout << "Your first name is: " << name << endl; + return 0; +} + +//************************************************************** +// Definition of function nameSlice. This function accepts a * +// character array as its argument. It scans the array looking * +// for a space. When it finds one, it replaces it with a null * +// terminator. * +//************************************************************** + +void nameSlice(char userName[]) +{ + int count = 0; // Loop counter + + // Locate the first space, or the null terminator if there + // are no spaces. + while (userName[count] != ' ' && userName[count] != '\0') + count++; + + // If a space was found, replace it with a null terminator. + if (userName[count] == ' ') + userName[count] = '\0'; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-14.cpp b/SourceCode/Chapter 10/Pr10-14.cpp new file mode 100755 index 0000000..6055629 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-14.cpp @@ -0,0 +1,49 @@ +// This program demonstrates a function, countChars, that counts +// the number of times a specific character appears in a string. +#include +using namespace std; + +int countChars(char *, char); // Function prototype + +int main() +{ + const int SIZE = 51; // Array size + char userString[SIZE]; // To hold a string + char letter; // The character to count + + // Get a string from the user. + cout << "Enter a string (up to 50 characters): "; + cin.getline(userString, SIZE); + + // Get a character to count occurrences of within the string. + cout << "Enter a character and I will tell you how many\n"; + cout << "times it appears in the string: "; + cin >> letter; + + // Display the number of times the character appears. + cout << letter << " appears "; + cout << countChars(userString, letter) << " times.\n"; + return 0; +} + +//**************************************************************** +// Definition of countChars. The parameter strPtr is a pointer * +// that points to a string. The parameter Ch is a character that * +// the function searches for in the string. The function returns * +// the number of times the character appears in the string. * +//**************************************************************** + +int countChars(char *strPtr, char ch) +{ + int times = 0; // Number of times ch appears in the string + + // Step through the string counting occurrences of ch. + while (*strPtr != '\0') + { + if (*strPtr == ch) // If the current character equals ch... + times++; // ... increment the counter + strPtr++; // Go to the next char in the string. + } + + return times; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-15.cpp b/SourceCode/Chapter 10/Pr10-15.cpp new file mode 100755 index 0000000..251c6f2 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-15.cpp @@ -0,0 +1,13 @@ +// This program demonstrates the string class. +#include +#include // Required for the string class. +using namespace std; + +int main() +{ + string movieTitle; + + movieTitle = "Wheels of Fury"; + cout << "My favorite movie is " << movieTitle << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-16.cpp b/SourceCode/Chapter 10/Pr10-16.cpp new file mode 100755 index 0000000..2993f43 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-16.cpp @@ -0,0 +1,15 @@ +// This program demonstrates how cin can read a string into +// a string class object. +#include +#include +using namespace std; + +int main() +{ + string name; + + cout << "What is your name? "; + cin >> name; + cout << "Good morning " << name << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-17.cpp b/SourceCode/Chapter 10/Pr10-17.cpp new file mode 100755 index 0000000..0007c7d --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-17.cpp @@ -0,0 +1,29 @@ +// This program uses the == operator to compare the string entered +// by the user with the valid stereo part numbers. +#include +#include +#include +using namespace std; + +int main() +{ + const double APRICE = 249.0; // Price for part A + const double BPRICE = 299.0; // Price for part B + string partNum; // Part mumber + + cout << "The stereo part numbers are:\n"; + cout << "\tBoom Box, part number S147-29A\n"; + cout << "\tShelf Model, part number S147-29B\n"; + cout << "Enter the part number of the stereo you\n"; + cout << "wish to purchase: "; + cin >> partNum; + cout << fixed << showpoint << setprecision(2); + + if (partNum == "S147-29A") + cout << "The price is $" << APRICE << endl; + else if (partNum == "S147-29B") + cout << "The price is $" << BPRICE << endl; + else + cout << partNum << " is not a valid part number.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-18.cpp b/SourceCode/Chapter 10/Pr10-18.cpp new file mode 100755 index 0000000..0889678 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-18.cpp @@ -0,0 +1,28 @@ +// This program uses relational operators to alphabetically +// sort two strings entered by the user. +#include +#include +using namespace std; + +int main () +{ + string name1, name2; + + // Get a name. + cout << "Enter a name (last name first): "; + getline(cin, name1); + + // Get another name. + cout << "Enter another name: "; + getline(cin, name2); + + // Display them in alphabetical order. + cout << "Here are the names sorted alphabetically:\n"; + if (name1 < name2) + cout << name1 << endl << name2 << endl; + else if (name1 > name2) + cout << name2 << endl << name1 << endl; + else + cout << "You entered the same name twice!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-19.cpp b/SourceCode/Chapter 10/Pr10-19.cpp new file mode 100755 index 0000000..43b056a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-19.cpp @@ -0,0 +1,14 @@ +// This program initializes a string object. +#include +#include +using namespace std; + +int main() +{ + string greeting; + string name("William Smith"); + + greeting = "Hello "; + cout << greeting << name << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-2.cpp b/SourceCode/Chapter 10/Pr10-2.cpp new file mode 100755 index 0000000..136121b --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-2.cpp @@ -0,0 +1,58 @@ +// This program tests a customer number to determine whether +// it is in the proper format. +#include +#include +using namespace std; + +// Function prototype +bool testNum(char [], int); + +int main() +{ + const int SIZE = 8; // Array size + char customer[SIZE]; // To hold a customer number + + // Get the customer number. + cout << "Enter a customer number in the form "; + cout << "LLLNNNN\n"; + cout << "(LLL = letters and NNNN = numbers): "; + cin.getline(customer, SIZE); + + // Determine whether it is valid. + if (testNum(customer, SIZE)) + cout << "That's a valid customer number.\n"; + else + { + cout << "That is not the proper format of the "; + cout << "customer number.\nHere is an example:\n"; + cout << " ABC1234\n"; + } + return 0; +} + +//********************************************************** +// Definition of function testNum. * +// This function determines whether the custNum parameter * +// holds a valid customer number. The size parameter is * +// the size of the custNum array. * +//********************************************************** + +bool testNum(char custNum[], int size) +{ + int count; // Loop counter + + // Test the first three characters for alphabetic letters. + for (count = 0; count < 3; count++) + { + if (!isalpha(custNum[count])) + return false; + } + + // Test the remaining characters for numeric digits. + for (count = 3; count < size - 1; count++) + { + if (!isdigit(custNum[count])) + return false; + } + return true; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-20.cpp b/SourceCode/Chapter 10/Pr10-20.cpp new file mode 100755 index 0000000..7c4b819 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-20.cpp @@ -0,0 +1,25 @@ +// This program demonstrates the C++ string class. +#include +#include +using namespace std; + +int main () +{ + // Define three string objects. + string str1, str2, str3; + + // Assign values to all three. + str1 = "ABC"; + str2 = "DEF"; + str3 = str1 + str2; + + // Display all three. + cout << str1 << endl; + cout << str2 << endl; + cout << str3 << endl; + + // Concatenate a string onto str3 and display it. + str3 += "GHI"; + cout << str3 << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-21.cpp b/SourceCode/Chapter 10/Pr10-21.cpp new file mode 100755 index 0000000..3f4044a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-21.cpp @@ -0,0 +1,16 @@ +// This program demonstrates a string +// object's length member function. +#include +#include +using namespace std; + +int main () +{ + string town; + + cout << "Where do you live? "; + cin >> town; + cout << "Your town's name has " << town.length() ; + cout << " characters\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-22.cpp b/SourceCode/Chapter 10/Pr10-22.cpp new file mode 100755 index 0000000..a26bb93 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-22.cpp @@ -0,0 +1,28 @@ +// This program demonstrates the C++ string class. +#include +#include +using namespace std; + +int main() +{ + // Define three string objects. + string str1, str2, str3; + + // Assign values to all three. + str1 = "ABC"; + str2 = "DEF"; + str3 = str1 + str2; + + // Use subscripts to display str3 one character + // at a time. + for (int x = 0; x < str3.size(); x++) + cout << str3[x]; + cout << endl; + + // Compare str1 with str2. + if (str1 < str2) + cout << "str1 is less than str2\n"; + else + cout << "str1 is not less than str2\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-23.cpp b/SourceCode/Chapter 10/Pr10-23.cpp new file mode 100755 index 0000000..396186f --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-23.cpp @@ -0,0 +1,43 @@ +// This program lets the user enter a number. The +// dollarFormat function formats the number as +// a dollar amount. +#include +#include +using namespace std; + +// Function prototype +void dollarFormat(string &); + +int main () +{ + string input; + + // Get the dollar amount from the user. + cout << "Enter a dollar amount in the form nnnnn.nn : "; + cin >> input; + dollarFormat(input); + cout << "Here is the amount formatted:\n"; + cout << input << endl; + return 0; +} + +//************************************************************ +// Definition of the dollarFormat function. This function * +// accepts a string reference object, which is assumed to * +// to hold a number with a decimal point. The function * +// formats the number as a dollar amount with commas and * +// a $ symbol. * +//************************************************************ + +void dollarFormat(string ¤cy) +{ + int dp; + + dp = currency.find('.'); // Find decimal point + if (dp > 3) // Insert commas + { + for (int x = dp - 3; x > 0; x -= 3) + currency.insert(x, ","); + } + currency.insert(0, "$"); // Insert dollar sign +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-3.cpp b/SourceCode/Chapter 10/Pr10-3.cpp new file mode 100755 index 0000000..64f9a3a --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-3.cpp @@ -0,0 +1,40 @@ +// This program calculates the area of a circle. It asks the user +// if he or she wishes to continue. A loop that demonstrates the +// toupper function repeats until the user enters 'y', 'Y', +// 'n', or 'N'. +#include +#include +#include +using namespace std; + +int main() +{ + const double PI = 3.14159; // Constant for Pi + double radius; // The circle's radius + char goAgain; // To hold Y or N + + cout << "This program calculates the area of a circle.\n"; + cout << fixed << setprecision(2); + + do + { + // Get the radius and display the area. + cout << "Enter the circle's radius: "; + cin >> radius; + cout << "The area is " << (PI * radius * radius); + cout << endl; + + // Does the user want to do this again? + cout << "Calculate another? (Y or N) "; + cin >> goAgain; + + // Validate the input. + while (toupper(goAgain) != 'Y' && toupper(goAgain) != 'N') + { + cout << "Please enter Y or N: "; + cin >> goAgain; + } + + } while (toupper(goAgain) == 'Y'); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-4.cpp b/SourceCode/Chapter 10/Pr10-4.cpp new file mode 100755 index 0000000..40da4ef --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-4.cpp @@ -0,0 +1,16 @@ +// This program contains string literals. +#include +using namespace std; + +int main() +{ + char again; + + do + { + cout << "C++ programming is great fun!" << endl; + cout << "Do you want to see the message again? "; + cin >> again; + } while (again == 'Y' || again == 'y'); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-5.cpp b/SourceCode/Chapter 10/Pr10-5.cpp new file mode 100755 index 0000000..a317b00 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-5.cpp @@ -0,0 +1,24 @@ +// This program displays a string stored in a char array. +#include +using namespace std; + +int main() +{ + const int SIZE = 80; // Array size + char line[SIZE]; // To hold a line of input + int count = 0; // Loop counter variable + + // Get a line of input. + cout << "Enter a sentence of no more than " + << (SIZE - 1) << " characters:\n"; + cin.getline(line, SIZE); + + // Display the input one character at a time. + cout << "The sentence you entered is:\n"; + while (line[count] != '\0') + { + cout << line[count]; + count++; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-6.cpp b/SourceCode/Chapter 10/Pr10-6.cpp new file mode 100755 index 0000000..ec53374 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-6.cpp @@ -0,0 +1,44 @@ +// This program uses the strstr function to search an array. +#include +#include // For strstr +using namespace std; + +int main() +{ + // Constants for array lengths + const int NUM_PRODS = 5; // Number of products + const int LENGTH = 27; // String length + + // Array of products + char products[NUM_PRODS][LENGTH] = + { "TV327 31 inch Television", + "CD257 CD Player", + "TA677 Answering Machine", + "CS109 Car Stereo", + "PC955 Personal Computer" }; + + char lookUp[LENGTH]; // To hold user's input + char *strPtr = nullptr; // To point to the found product + int index; // Loop counter + + // Prompt the usr for a product number. + cout << "\tProduct Database\n\n"; + cout << "Enter a product number to search for: "; + cin.getline(lookUp, LENGTH); + + // Search the array for a matching substring + for (index = 0; index < NUM_PRODS; index++) + { + strPtr = strstr(products[index], lookUp); + if (strPtr != nullptr) + break; + } + + // If a matching substring was found, display the product info. + if (strPtr != nullptr) + cout << products[index] << endl; + else + cout << "No matching product was found.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-7.cpp b/SourceCode/Chapter 10/Pr10-7.cpp new file mode 100755 index 0000000..879f9ba --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-7.cpp @@ -0,0 +1,26 @@ +// This program tests two C-strings for equality +// using the strcmp function. +#include +#include +using namespace std; + +int main() +{ + // Two arrays for two strings. + const int LENGTH = 40; + char firstString[LENGTH], secondString[LENGTH]; + + // Read two strings. + cout << "Enter a string: "; + cin.getline(firstString, LENGTH); + cout << "Enter another string: "; + cin.getline(secondString, LENGTH); + + // Compare the strings for equality with strcmp. + if (strcmp(firstString, secondString) == 0) + cout << "You entered the same string twice.\n"; + else + cout << "The strings are not the same.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-8.cpp b/SourceCode/Chapter 10/Pr10-8.cpp new file mode 100755 index 0000000..2bb9b1c --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-8.cpp @@ -0,0 +1,38 @@ +// This program uses strcmp to compare the string entered +// by the user with the valid stereo part numbers. +#include +#include +#include +using namespace std; + +int main() +{ + // Price of parts. + const double A_PRICE = 249.0, + B_PRICE = 299.0; + + // Character array for part number. + const int PART_LENGTH = 8; + char partNum[PART_LENGTH]; + + // Instruct the user to enter a part number. + cout << "The stereo part numbers are:\n" + << "\tBoom Box, part number S147-29A\n" + << "\tShelf Model, part number S147-29B\n" + << "Enter the part number of the stereo you\n" + << "wish to purchase: "; + + // Read a part number of at most 8 characters. + cin >> partNum; + + // Determine what user entered using strcmp + // and print its price. + cout << showpoint << fixed << setprecision(2); + if (strcmp(partNum, "S147-29A") == 0) + cout << "The price is $" << A_PRICE << endl; + else if (strcmp(partNum, "S147-29B") == 0) + cout << "The price is $" << B_PRICE << endl; + else + cout << partNum << " is not a valid part number.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 10/Pr10-9.cpp b/SourceCode/Chapter 10/Pr10-9.cpp new file mode 100755 index 0000000..a38ccd3 --- /dev/null +++ b/SourceCode/Chapter 10/Pr10-9.cpp @@ -0,0 +1,29 @@ +// This program uses the return value of strcmp to +// alphabetically sort two strings entered by the user. +#include +#include +using namespace std; + +int main() +{ + // Two arrays to hold two strings. + const int NAME_LENGTH = 30; + char name1[NAME_LENGTH], name2[NAME_LENGTH]; + + // Read two strings. + cout << "Enter a name (last name first): "; + cin.getline(name1, NAME_LENGTH); + cout << "Enter another name: "; + cin.getline(name2, NAME_LENGTH); + + // Print the two strings in alphabetical order. + cout << "Here are the names sorted alphabetically:\n"; + if (strcmp(name1, name2) < 0) + cout << name1 << endl << name2 << endl; + else if (strcmp(name1, name2) > 0) + cout << name2 << endl << name1 << endl; + else + cout << "You entered the same name twice!\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-1.cpp b/SourceCode/Chapter 11/Pr11-1.cpp new file mode 100755 index 0000000..524fd32 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-1.cpp @@ -0,0 +1,49 @@ +// This program demonstrates the use of structures. +#include +#include +#include +using namespace std; + +struct PayRoll +{ + int empNumber; // Employee number + string name; // Employee's name + double hours; // Hours worked + double payRate; // Hourly payRate + double grossPay; // Gross Pay +}; + +int main() +{ + PayRoll employee; // employee is a PayRoll structure. + + // Get the employee's number. + cout << "Enter the employee's number: "; + cin >> employee.empNumber; + + // Get the employee's name. + cout << "Enter the employee's name: "; + cin.ignore(); // To skip the remaining '\n' character + getline(cin, employee.name); + + // Get the hours worked by the employee. + cout << "How many hours did the employee work? "; + cin >> employee.hours; + + // Get the employee's hourly pay rate. + cout << "What is the employee's hourly payRate? "; + cin >> employee.payRate; + + // Calculate the employee's gross pay. + employee.grossPay = employee.hours * employee.payRate; + + // Display the employee data. + cout << "Here is the employee's payroll data:\n"; + cout << "name: " << employee.name << endl; + cout << "Number: " << employee.empNumber << endl; + cout << "hours worked: " << employee.hours << endl; + cout << "Hourly payRate: " << employee.payRate << endl; + cout << fixed << showpoint << setprecision(2); + cout << "Gross Pay: $" << employee.grossPay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-10.cpp b/SourceCode/Chapter 11/Pr11-10.cpp new file mode 100755 index 0000000..ce0b6f9 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-10.cpp @@ -0,0 +1,57 @@ +// This program demonstrates an anonymous union. +#include +#include +using namespace std; + +int main() +{ + union // Anonymous union + { + int hours; + float sales; + }; + + char payType; // To hold the pay type + float payRate; // Hourly pay rate + float grossPay; // Gross pay + + cout << fixed << showpoint << setprecision(2); + cout << "This program calculates either hourly wages or\n"; + cout << "sales commission.\n"; + + // Get the pay type, hourly or commission. + cout << "Enter H for hourly wages or C for commission: "; + cin >> payType; + + // Determine the gross pay, depending on the pay type. + if (payType == 'H' || payType == 'h') + { + // This is an hourly paid employee. Get the + // pay rate and hours worked. + cout << "What is the hourly pay rate? "; + cin >> payRate; + cout << "How many hours were worked? "; + cin >> hours; // Anonymous union member + + // Calculate and display the gross pay. + grossPay = hours * payRate; + cout << "Gross pay: $" << grossPay << endl; + } + else if (payType == 'C' || payType == 'c') + { + // This is a commission-paid employee. Get the + // amount of sales. + cout << "What are the total sales for this employee? "; + cin >> sales; // Anonymous union member + + // Calculate and display the gross pay. + grossPay = sales * 0.10; + cout << "Gross pay: $" << grossPay << endl; + } + else + { + // The user made an invalid selection. + cout << payType << " is not a valid selection.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-11.cpp b/SourceCode/Chapter 11/Pr11-11.cpp new file mode 100755 index 0000000..318c85c --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-11.cpp @@ -0,0 +1,32 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; + +int main() +{ + const int NUM_DAYS = 5; // The number of days + double sales[NUM_DAYS]; // To hold sales for each day + double total = 0.0; // Accumulator + int index; // Loop counter + + // Get the sales for each day. + for (index = MONDAY; index <= FRIDAY; index++) + { + cout << "Enter the sales for day " + << index << ": "; + cin >> sales[index]; + } + + // Calculate the total sales. + for (index = MONDAY; index <= FRIDAY; index++) + total += sales[index]; + + // Display the total. + cout << "The total sales are $" << setprecision(2) + << fixed << total << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-12.cpp b/SourceCode/Chapter 11/Pr11-12.cpp new file mode 100755 index 0000000..0c5b2e9 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-12.cpp @@ -0,0 +1,34 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; + +int main() +{ + const int NUM_DAYS = 5; // The number of days + double sales[NUM_DAYS]; // To hold sales for each day + double total = 0.0; // Accumulator + Day workDay; // Loop counter + + // Get the sales for each day. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + { + cout << "Enter the sales for day " + << workDay << ": "; + cin >> sales[workDay]; + } + + // Calcualte the total sales. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + total += sales[workDay]; + + // Display the total. + cout << "The total sales are $" << setprecision(2) + << fixed << total << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-13.cpp b/SourceCode/Chapter 11/Pr11-13.cpp new file mode 100755 index 0000000..90490c0 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-13.cpp @@ -0,0 +1,60 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; + +// Function prototype +void displayDayName(Day); + +int main() +{ + const int NUM_DAYS = 5; // The number of days + double sales[NUM_DAYS]; // To hold sales for each day + double total = 0.0; // Accumulator + Day workDay; // Loop counter + + // Get the sales for each day. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + { + cout << "Enter the sales for day "; + displayDayName(workDay); + cout << ": "; + cin >> sales[workDay]; + } + + // Calcualte the total sales. + for (workDay = MONDAY; workDay <= FRIDAY; + workDay = static_cast(workDay + 1)) + total += sales[workDay]; + + // Display the total. + cout << "The total sales are $" << setprecision(2) + << fixed << total << endl; + + return 0; +} + +//********************************************************** +// Definition of the displayDayName function * +// This function accepts an argumet of the Day type and * +// displays the corresponding name of the day. * +//********************************************************** + +void displayDayName(Day d) +{ + switch(d) + { + case MONDAY : cout << "Monday"; + break; + case TUESDAY : cout << "Tuesday"; + break; + case WEDNESDAY : cout << "Wednesday"; + break; + case THURSDAY : cout << "Thursday"; + break; + case FRIDAY : cout << "Friday"; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-14.cpp b/SourceCode/Chapter 11/Pr11-14.cpp new file mode 100755 index 0000000..c12965b --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-14.cpp @@ -0,0 +1,21 @@ +// This program demonstrates an enumerated data type. +#include +#include +using namespace std; + +int main() +{ + enum Water { FREEZING = 32, BOILING = 212 }; + int waterTemp; // To hold the water temperature + + cout << "Enter the current water temperature: "; + cin >> waterTemp; + if (waterTemp <= FREEZING) + cout << "The water is frozen.\n"; + else if (waterTemp >= BOILING) + cout << "The water is boiling.\n"; + else + cout << "The water is not frozen or boiling.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-2.cpp b/SourceCode/Chapter 11/Pr11-2.cpp new file mode 100755 index 0000000..f13f557 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-2.cpp @@ -0,0 +1,38 @@ +// This program stores data about a circle in a structure. +#include +#include // For the pow function +#include +using namespace std; + +// Constant for Pi. +const double PI = 3.14159; + +// Structure declaration +struct Circle +{ + double radius; // A circle's radius + double diameter; // A circle's diameter + double area; // A circle's area +}; + +int main() +{ + Circle c; // Define a structure variable + + // Get the circle's diameter. + cout << "Enter the diameter of a circle: "; + cin >> c.diameter; + + // Calculate the circle's radius. + c.radius = c.diameter / 2; + + // Calculate the circle's area. + c.area = PI * pow(c.radius, 2.0); + + // Display the circle data. + cout << fixed << showpoint << setprecision(2); + cout << "The radius and area of the circle are:\n"; + cout << "Radius: " << c.radius << endl; + cout << "Area: " << c.area << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-3.cpp b/SourceCode/Chapter 11/Pr11-3.cpp new file mode 100755 index 0000000..ee4fe65 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-3.cpp @@ -0,0 +1,40 @@ +// This program demonstrates partially initialized +// structure variables. +#include +#include +#include +using namespace std; + +struct EmployeePay +{ + string name; // Employee name + int empNum; // Employee number + double payRate; // Hourly pay rate + double hours; // Hours worked + double grossPay; // Gross pay +}; + +int main() +{ + EmployeePay employee1 = {"Betty Ross", 141, 18.75}; + EmployeePay employee2 = {"Jill Sandburg", 142, 17.50}; + + cout << fixed << showpoint << setprecision(2); + + // Calculate pay for employee1 + cout << "Name: " << employee1.name << endl; + cout << "Employee Number: " << employee1.empNum << endl; + cout << "Enter the hours worked by this employee: "; + cin >> employee1.hours; + employee1.grossPay = employee1.hours * employee1.payRate; + cout << "Gross Pay: " << employee1.grossPay << endl << endl; + + // Calculate pay for employee2 + cout << "Name: " << employee2.name << endl; + cout << "Employee Number: " << employee2.empNum << endl; + cout << "Enter the hours worked by this employee: "; + cin >> employee2.hours; + employee2.grossPay = employee2.hours * employee2.payRate; + cout << "Gross Pay: " << employee2.grossPay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-4.cpp b/SourceCode/Chapter 11/Pr11-4.cpp new file mode 100755 index 0000000..c54a6af --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-4.cpp @@ -0,0 +1,47 @@ +// This program uses an array of structures. +#include +#include +using namespace std; + +struct PayInfo +{ + int hours; // Hours Worked + double payRate; // Hourly Pay Rate +}; + +int main() +{ + const int NUM_WORKERS = 3; // Number of workers + PayInfo workers[NUM_WORKERS]; // Array of structures + int index; // Loop counter + + // Get employee pay data. + cout << "Enter the hours worked by " << NUM_WORKERS + << " employees and their hourly rates.\n"; + + for (index = 0; index < NUM_WORKERS; index++) + { + // Get the hours worked by an employee. + cout << "Hours worked by employee #" << (index + 1); + cout << ": "; + cin >> workers[index].hours; + + // Get the employee's hourly pay rate. + cout << "Hourly pay rate for employee #"; + cout << (index + 1) << ": "; + cin >> workers[index].payRate; + cout << endl; + } + + // Display each employee's gross pay. + cout << "Here is the gross pay for each employee:\n"; + cout << fixed << showpoint << setprecision(2); + for (index = 0; index < NUM_WORKERS; index++) + { + double gross; + gross = workers[index].hours * workers[index].payRate; + cout << "Employee #" << (index + 1); + cout << ": $" << gross << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-5.cpp b/SourceCode/Chapter 11/Pr11-5.cpp new file mode 100755 index 0000000..6e98928 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-5.cpp @@ -0,0 +1,77 @@ +// This program uses nested structures. +#include +#include +using namespace std; + +// The Date structure holds data about a date. +struct Date +{ + int month; + int day; + int year; +}; + +// The Place structure holds a physical address. +struct Place +{ + string address; + string city; + string state; + string zip; +}; + +// The EmployeeInfo structure holds an employee's data. +struct EmployeeInfo +{ + string name; + int employeeNumber; + Date birthDate; // Nested structure + Place residence; // Nested structure +}; + +int main() +{ + // Define a structure variable to hold info about the manager. + EmployeeInfo manager; + + // Get the manager's name and employee number + cout << "Enter the manager's name: "; + getline(cin, manager.name); + cout << "Enter the manager's employee number: "; + cin >> manager.employeeNumber; + + // Get the manager's birth date + cout << "Now enter the manager's date of birth.\n"; + cout << "Month (up to 2 digits): "; + cin >> manager.birthDate.month; + cout << "Day (up to 2 digits): "; + cin >> manager.birthDate.day; + cout << "Year: "; + cin >> manager.birthDate.year; + cin.ignore(); // Skip the remaining newline character + + // Get the manager's residence information + cout << "Enter the manager's street address: "; + getline(cin, manager.residence.address); + cout << "City: "; + getline(cin, manager.residence.city); + cout << "State: "; + getline(cin, manager.residence.state); + cout << "ZIP Code: "; + getline(cin, manager.residence.zip); + + // Display the information just entered + cout << "\nHere is the manager's information:\n"; + cout << manager.name << endl; + cout << "Employee number " << manager.employeeNumber << endl; + cout << "Date of birth: "; + cout << manager.birthDate.month << "-"; + cout << manager.birthDate.day << "-"; + cout << manager.birthDate.year << endl; + cout << "Place of residence:\n"; + cout << manager.residence.address << endl; + cout << manager.residence.city << ", "; + cout << manager.residence.state << " "; + cout << manager.residence.zip << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-6.cpp b/SourceCode/Chapter 11/Pr11-6.cpp new file mode 100755 index 0000000..67c40fe --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-6.cpp @@ -0,0 +1,68 @@ +// This program has functions that accept structure variables +// as arguments. +#include +#include +#include +using namespace std; + +struct InventoryItem +{ + int partNum; // Part number + string description; // Item description + int onHand; // Units on hand + double price; // Unit price +}; + +// Function Prototypes +void getItem(InventoryItem&); // Argument passed by reference +void showItem(InventoryItem); // Argument passed by value + +int main() +{ + InventoryItem part; + + getItem(part); + showItem(part); + return 0; +} + +//*********************************************************** +// Definition of function getItem. This function uses * +// a structure reference variable as its parameter. It asks * +// the user for information to store in the structure. * +//*********************************************************** + +void getItem(InventoryItem &p) // Uses a reference parameter +{ + // Get the part number. + cout << "Enter the part number: "; + cin >> p.partNum; + + // Get the part description. + cout << "Enter the part description: "; + cin.ignore(); // Ignore the remaining newline character + getline(cin, p.description); + + // Get the quantity on hand. + cout << "Enter the quantity on hand: "; + cin >> p.onHand; + + // Get the unit price. + cout << "Enter the unit price: "; + cin >> p.price; +} + +//*********************************************************** +// Definition of function showItem. This function accepts * +// an argument of the InventoryItem structure type. The * +// contents of the structure is displayed. * +//*********************************************************** + +void showItem(InventoryItem p) +{ + cout << fixed << showpoint << setprecision(2); + cout << "Part Number: " << p.partNum << endl; + cout << "Description: " << p.description << endl; + cout << "Units On Hand: " << p.onHand << endl; + cout << "Price: $" << p.price << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-7.cpp b/SourceCode/Chapter 11/Pr11-7.cpp new file mode 100755 index 0000000..0b51753 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-7.cpp @@ -0,0 +1,60 @@ +// This program uses a function to return a structure. This +// is a modification of Program 11-2. +#include +#include +#include // For the pow function +using namespace std; + +// Constant for Pi. +const double PI = 3.14159; + +// Structure declaration +struct Circle +{ + double radius; // A circle's radius + double diameter; // A circle's diameter + double area; // A circle's area +}; + +// Function prototype +Circle getInfo(); + +int main() +{ + Circle c; // Define a structure variable + + // Get data about the circle. + c = getInfo(); + + // Calculate the circle's area. + c.area = PI * pow(c.radius, 2.0); + + // Display the circle data. + cout << "The radius and area of the circle are:\n"; + cout << fixed << setprecision(2); + cout << "Radius: " << c.radius << endl; + cout << "Area: " << c.area << endl; + return 0; +} + +//*************************************************************** +// Definition of function getInfo. This function uses a local * +// variable, tempCircle, which is a circle structure. The user * +// enters the diameter of the circle, which is stored in * +// tempCircle.diameter. The function then calculates the radius * +// which is stored in tempCircle.radius. tempCircle is then * +// returned from the function. * +//*************************************************************** + +Circle getInfo() +{ + Circle tempCircle; // Temporary structure variable + + // Store circle data in the temporary variable. + cout << "Enter the diameter of a circle: "; + cin >> tempCircle.diameter; + tempCircle.radius = tempCircle.diameter / 2.0; + + // Return the temporary variable. + return tempCircle; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-8.cpp b/SourceCode/Chapter 11/Pr11-8.cpp new file mode 100755 index 0000000..2cfffbf --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-8.cpp @@ -0,0 +1,59 @@ +// This program demonstrates a function that uses a +// pointer to a structure variable as a parameter. +#include +#include +#include +using namespace std; + +struct Student +{ + string name; // Student's name + int idNum; // Student ID number + int creditHours; // Credit hours enrolled + double gpa; // Current GPA +}; + +void getData(Student *); // Function prototype + +int main() +{ + Student freshman; + + // Get the student data. + cout << "Enter the following student data:\n"; + getData(&freshman); // Pass the address of freshman. + cout << "\nHere is the student data you entered:\n"; + + // Now display the data stored in freshman + cout << setprecision(3); + cout << "Name: " << freshman.name << endl; + cout << "ID Number: " << freshman.idNum << endl; + cout << "Credit Hours: " << freshman.creditHours << endl; + cout << "GPA: " << freshman.gpa << endl; + return 0; +} + +//******************************************************* +// Definition of function getData. Uses a pointer to a * +// Student structure variable. The user enters student * +// information, which is stored in the variable. * +//******************************************************* + +void getData(Student *s) +{ + // Get the student name. + cout << "Student name: "; + getline(cin, s->name); + + // Get the student ID number. + cout << "Student ID Number: "; + cin >> s->idNum; + + // Get the credit hours enrolled. + cout << "Credit Hours Enrolled: "; + cin >> s->creditHours; + + // Get the GPA. + cout << "Current GPA: "; + cin >> s->gpa; +} \ No newline at end of file diff --git a/SourceCode/Chapter 11/Pr11-9.cpp b/SourceCode/Chapter 11/Pr11-9.cpp new file mode 100755 index 0000000..0fa03d7 --- /dev/null +++ b/SourceCode/Chapter 11/Pr11-9.cpp @@ -0,0 +1,58 @@ +// This program demonstrates a union. +#include +#include +using namespace std; + +union PaySource +{ + int hours; // Hours worked + float sales; // Amount of sales +}; + +int main() +{ + PaySource employee1; // Define a union variable + char payType; // To hold the pay type + float payRate; // Hourly pay rate + float grossPay; // Gross pay + + cout << fixed << showpoint << setprecision(2); + cout << "This program calculates either hourly wages or\n"; + cout << "sales commission.\n"; + + // Get the pay type, hourly or commission. + cout << "Enter H for hourly wages or C for commission: "; + cin >> payType; + + // Determine the gross pay, depending on the pay type. + if (payType == 'H' || payType == 'h') + { + // This is an hourly paid employee. Get the + // pay rate and hours worked. + cout << "What is the hourly pay rate? "; + cin >> payRate; + cout << "How many hours were worked? "; + cin >> employee1.hours; + + // Calculate and display the gross pay. + grossPay = employee1.hours * payRate; + cout << "Gross pay: $" << grossPay << endl; + } + else if (payType == 'C' || payType == 'c') + { + // This is a commission-paid employee. Get the + // amount of sales. + cout << "What are the total sales for this employee? "; + cin >> employee1.sales; + + // Calculate and display the gross pay. + grossPay = employee1.sales * 0.10; + cout << "Gross pay: $" << grossPay << endl; + } + else + { + // The user made an invalid selection. + cout << payType << " is not a valid selection.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Inventory.dat b/SourceCode/Chapter 12/Inventory.dat new file mode 100755 index 0000000..382ddfd Binary files /dev/null and b/SourceCode/Chapter 12/Inventory.dat differ diff --git a/SourceCode/Chapter 12/Pr12-1.cpp b/SourceCode/Chapter 12/Pr12-1.cpp new file mode 100755 index 0000000..a1cde0c --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-1.cpp @@ -0,0 +1,20 @@ +// This program uses an fstream object to write data to a file. +#include +#include +using namespace std; + +int main() +{ + fstream dataFile; + + cout << "Opening file...\n"; + dataFile.open("demofile.txt", ios::out); // Open for output + cout << "Now writing data to the file.\n"; + dataFile << "Jones\n"; // Write line 1 + dataFile << "Smith\n"; // Write line 2 + dataFile << "Willis\n"; // Write line 3 + dataFile << "Davis\n"; // Write line 4 + dataFile.close(); // Close the file + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-10.cpp b/SourceCode/Chapter 12/Pr12-10.cpp new file mode 100755 index 0000000..f4eab8b --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-10.cpp @@ -0,0 +1,44 @@ +// This program asks the user for a file name. The file is +// opened and its contents are displayed on the screen. +#include +#include +#include +using namespace std; + +int main() +{ + string fileName; // To hold the file name + char ch; // To hold a character + fstream file; // File stream object + + // Get the file name + cout << "Enter a file name: "; + cin >> fileName; + + // Open the file. + file.open(fileName, ios::in); + + // If the file was successfully opened, continue. + if (file) + { + // Get a character from the file. + file.get(ch); + + // While the last read opeation was + // successful, continue. + while (file) + { + // Display the last character read. + cout << ch; + + // Read the next character + file.get(ch); + } + + // Close the file. + file.close(); + } + else + cout << fileName << " could not be opened.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-11.cpp b/SourceCode/Chapter 12/Pr12-11.cpp new file mode 100755 index 0000000..49e3712 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-11.cpp @@ -0,0 +1,29 @@ +// This program demonstrates the put member function. +#include +#include +using namespace std; + +int main() +{ + char ch; // To hold a character + + // Open the file for output. + fstream dataFile("sentence.txt", ios::out); + + cout << "Type the sentence and be sure to end it with a "; + cout << "period.\n"; + + // Get a sentence from the user one character at a time + // and write each character to the file. + cin.get(ch); + while (ch != '.') + { + dataFile.put(ch); + cin.get(ch); + } + dataFile.put(ch); // Write the period. + + // Close the file. + dataFile.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-12.cpp b/SourceCode/Chapter 12/Pr12-12.cpp new file mode 100755 index 0000000..d2e7953 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-12.cpp @@ -0,0 +1,50 @@ +// This program demonstrates reading from one file and writing +// to a second file. +#include +#include +#include +#include // Needed for the toupper function. +using namespace std; + +int main() +{ + string fileName; // To hold the file name + char ch; // To hold a character + ifstream inFile; // Input file + + // Open a file for output. + ofstream outFile("out.txt"); + + // Get the input file name. + cout << "Enter a file name: "; + cin >> fileName; + + // Open the file for input. + inFile.open(fileName); + + // If the input file opened successfully, continue. + if (inFile) + { + // Read a char from file 1. + inFile.get(ch); + + // While the last read operation was + // successful, continue. + while (inFile) + { + // Write uppercase char to file 2. + outFile.put(toupper(ch)); + + // Read another char from file 1. + inFile.get(ch); + } + + // Close the two files. + inFile.close(); + outFile.close(); + cout << "File conversion done.\n"; + } + else + cout << "Cannot open " << fileName << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-13.cpp b/SourceCode/Chapter 12/Pr12-13.cpp new file mode 100755 index 0000000..9a2ccb8 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-13.cpp @@ -0,0 +1,37 @@ +// This program uses the write and read functions. +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 4; + char data[SIZE] = { 'A', 'B', 'C', 'D' }; + fstream file; + + // Open the file for output in binary mode. + file.open("test.dat", ios::out | ios::binary); + + // Write the contents of the array to the file. + cout << "Writing the characters to the file.\n"; + file.write(data, sizeof(data)); + + // Close the file. + file.close(); + + // Open the file for input in binary mode. + file.open("test.dat", ios::in | ios::binary); + + // Read the contents of the file into the array. + cout << "Now reading the data back into memory.\n"; + file.read(data, sizeof(data)); + + // Display the contents of the array. + for (int count = 0; count < SIZE; count++) + cout << data[count] << " "; + cout << endl; + + // Close the file. + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-14.cpp b/SourceCode/Chapter 12/Pr12-14.cpp new file mode 100755 index 0000000..d1a9fa0 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-14.cpp @@ -0,0 +1,37 @@ +// This program uses the write and read functions. +#include +#include +using namespace std; + +int main() +{ + const int SIZE = 10; + fstream file; + int numbers[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + + // Open the file for output in binary mode. + file.open("numbers.dat", ios::out | ios::binary); + + // Write the contents of the array to the file. + cout << "Writing the data to the file.\n"; + file.write(reinterpret_cast(numbers), sizeof(numbers)); + + // Close the file. + file.close(); + + // Open the file for input in binary mode. + file.open("numbers.dat", ios::in | ios::binary); + + // Read the contents of the file into the array. + cout << "Now reading the data back into memory.\n"; + file.read(reinterpret_cast(numbers), sizeof(numbers)); + + // Display the contents of the array. + for (int count = 0; count < SIZE; count++) + cout << numbers[count] << " "; + cout << endl; + + // Close the file. + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-15.cpp b/SourceCode/Chapter 12/Pr12-15.cpp new file mode 100755 index 0000000..917d87b --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-15.cpp @@ -0,0 +1,57 @@ +// This program uses a structure variable to store a record to a file. +#include +#include +using namespace std; + +// Array sizes +const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; + +// Declare a structure for the record. +struct Info +{ + char name[NAME_SIZE]; + int age; + char address1[ADDR_SIZE]; + char address2[ADDR_SIZE]; + char phone[PHONE_SIZE]; +}; + +int main() +{ + Info person; // To hold info about a person + char again; // To hold Y or N + + // Open a file for binary output. + fstream people("people.dat", ios::out | ios::binary); + + do + { + // Get data about a person. + cout << "Enter the following data about a " + << "person:\n"; + cout << "Name: "; + cin.getline(person.name, NAME_SIZE); + cout << "Age: "; + cin >> person.age; + cin.ignore(); // Skip over the remaining newline. + cout << "Address line 1: "; + cin.getline(person.address1, ADDR_SIZE); + cout << "Address line 2: "; + cin.getline(person.address2, ADDR_SIZE); + cout << "Phone: "; + cin.getline(person.phone, PHONE_SIZE); + + // Write the contents of the person structure to the file. + people.write(reinterpret_cast(&person), + sizeof(person)); + + // Determine wheter the user wants to write another record. + cout << "Do you want to enter another record? "; + cin >> again; + cin.ignore(); // Skip over the remaining newline. + } while (again == 'Y' || again == 'y'); + + // Close the file. + people.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-16.cpp b/SourceCode/Chapter 12/Pr12-16.cpp new file mode 100755 index 0000000..8d78b8e --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-16.cpp @@ -0,0 +1,68 @@ +// This program uses a structure variable to read a record from a file. +#include +#include +using namespace std; + +// Array sizes +const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; + +// Declare a structure for the record. +struct Info +{ + char name[NAME_SIZE]; + int age; + char address1[ADDR_SIZE]; + char address2[ADDR_SIZE]; + char phone[PHONE_SIZE]; +}; + +int main() +{ + Info person; // To hold info about a person + fstream people; // File stream object + + // Open a file for input in binary mode. + people.open("people.dat", ios::in | ios::binary); + + // Test for errors. + if (!people) + { + cout << "Error opening file. Program aborting.\n"; + return 0; + } + + cout << "Here are the people in the file: \n\n"; + // Read the first record from the file. + people.read(reinterpret_cast(&person), + sizeof(person)); + + // While not at the end of the file, + // display the records. + while (!people.eof()) + { + // Display the record. + cout << "Name: "; + cout << person.name << endl; + cout << "Age: "; + cout << person.age << endl; + cout << "Address line 1: "; + cout << person.address1 << endl; + cout << "Address line 2: "; + cout << person.address2 << endl; + cout << "Phone: "; + cout << person.phone << endl; + + // Wait for the user to press the Enter key. + cout << "\nPress the Enter key to see the next record.\n"; + cin.get(); + + // Read the next record from the file. + people.read(reinterpret_cast(&person), + sizeof(person)); + } + + // Close the file. + cout << "That's all the data in the file!\n"; + people.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-17.cpp b/SourceCode/Chapter 12/Pr12-17.cpp new file mode 100755 index 0000000..7e16121 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-17.cpp @@ -0,0 +1,33 @@ +// This program demonstrates the seekg function. +#include +#include +using namespace std; + +int main() +{ + char ch; // To hold a character + + // Open the file for input. + fstream file("letters.txt", ios::in); + + // Move to byte 5 from the beginning of the file + // (the 6th byte) and read the character there. + file.seekg(5L, ios::beg); + file.get(ch); + cout << "Byte 5 from beginning: " << ch << endl; + + // Move to the 10th byte from the end of the file + // and read the character there. + file.seekg(-10L, ios::end); + file.get(ch); + cout << "10th byte from end: " << ch << endl; + + // Move to byte 3 from the current position + // (the 4th byte) and read the character there. + file.seekg(3L, ios::cur); + file.get(ch); + cout << "Byte 3 from current: " << ch << endl; + + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-18.cpp b/SourceCode/Chapter 12/Pr12-18.cpp new file mode 100755 index 0000000..4082cd7 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-18.cpp @@ -0,0 +1,82 @@ +// This program randomly reads a record of data from a file. +#include +#include +using namespace std; + +const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14; + +// Declare a structure for the record. +struct Info +{ + char name[NAME_SIZE]; + int age; + char address1[ADDR_SIZE]; + char address2[ADDR_SIZE]; + char phone[PHONE_SIZE]; +}; + +// Function Prototypes +long byteNum(int); +void showRec(Info); + +int main() +{ + Info person; // To hold info about a person + fstream people; // File stream object + + // Open the file for input in binary mode. + people.open("people.dat", ios::in | ios::binary); + + // Test for errors. + if (!people) + { + cout << "Error opening file. Program aborting.\n"; + return 0; + } + + // Read and display record 1 (the second record). + cout << "Here is record 1:\n"; + people.seekg(byteNum(1), ios::beg); + people.read(reinterpret_cast(&person), sizeof(person)); + showRec(person); + + // Read and display record 0 (the first record). + cout << "\nHere is record 0:\n"; + people.seekg(byteNum(0), ios::beg); + people.read(reinterpret_cast(&person), sizeof(person)); + showRec(person); + + // Close the file. + people.close(); + return 0; +} + +//************************************************************ +// Definition of function byteNum. Accepts an integer as * +// its argument. Returns the byte number in the file of the * +// record whose number is passed as the argument. * +//************************************************************ + +long byteNum(int recNum) +{ + return sizeof(Info) * recNum; +} + +//************************************************************ +// Definition of function showRec. Accepts an Info structure * +// as its argument, and displays the structure's contents. * +//************************************************************ + +void showRec(Info record) +{ + cout << "Name: "; + cout << record.name << endl; + cout << "Age: "; + cout << record.age << endl; + cout << "Address line 1: "; + cout << record.address1 << endl; + cout << "Address line 2: "; + cout << record.address2 << endl; + cout << "Phone: "; + cout << record.phone << endl; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-19.cpp b/SourceCode/Chapter 12/Pr12-19.cpp new file mode 100755 index 0000000..5a2fda4 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-19.cpp @@ -0,0 +1,53 @@ +// This program demonstrates the tellg function. +#include +#include +using namespace std; + +int main() +{ + long offset; // To hold an offset amount + long numBytes; // To hold the file size + char ch; // To hold a character + char again; // To hold Y or N + + // Open the file for input. + fstream file("letters.txt", ios::in); + + // Determine the number of bytes in the file. + file.seekg(0L, ios::end); + numBytes = file.tellg(); + cout << "The file has " << numBytes << " bytes.\n"; + + // Go back to the beginning of the file. + file.seekg(0L, ios::beg); + + // Let the user move around within the file. + do + { + // Display the current read position. + cout << "Currently at position " << file.tellg() << endl; + + // Get a byte number from the user. + cout << "Enter an offset from the beginning of the file: "; + cin >> offset; + + // Move the read position to that byte, read the + // character there, and display it. + if (offset >= numBytes) // Past the end of the file? + cout << "Cannot read past the end of the file.\n"; + else + { + file.seekg(offset, ios::beg); + file.get(ch); + cout << "Character read: " << ch << endl; + } + + // Does the user want to try this again? + cout << "Do it again? "; + cin >> again; + } while (again == 'Y' || again == 'y'); + + // Close the file. + file.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-2.cpp b/SourceCode/Chapter 12/Pr12-2.cpp new file mode 100755 index 0000000..5ca5612 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-2.cpp @@ -0,0 +1,31 @@ +// This program writes data to a file, closes the file, +// then reopens the file and appends more data. +#include +#include +using namespace std; + +int main() +{ + ofstream dataFile; + + cout << "Opening file...\n"; + // Open the file in output mode. + dataFile.open("demofile.txt", ios::out); + cout << "Now writing data to the file.\n"; + dataFile << "Jones\n"; // Write line 1 + dataFile << "Smith\n"; // Write line 2 + cout << "Now closing the file.\n"; + dataFile.close(); // Close the file + + cout << "Opening the file again...\n"; + // Open the file in append mode. + dataFile.open("demofile.txt", ios::out | ios::app); + cout << "Writing more data to the file.\n"; + dataFile << "Willis\n"; // Write line 3 + dataFile << "Davis\n"; // Write line 4 + cout << "Now closing the file.\n"; + dataFile.close(); // Close the file + + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-20.cpp b/SourceCode/Chapter 12/Pr12-20.cpp new file mode 100755 index 0000000..55b6025 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-20.cpp @@ -0,0 +1,37 @@ +// This program sets up a file of blank inventory records. +#include +#include +using namespace std; + +// Constants +const int DESC_SIZE = 31; +const int NUM_RECORDS = 5; + +// Declaration of InventoryItem structure +struct InventoryItem +{ + char desc[DESC_SIZE]; + int qty; + double price; +}; + +int main() +{ + // Create an empty InventoryItem structure. + InventoryItem record = { "", 0, 0.0 }; + + // Open the file for binary output. + fstream inventory("Inventory.dat", ios::out | ios::binary); + + // Write the blank records. + for (int count = 0; count < NUM_RECORDS; count++) + { + cout << "Now writing record " << count << endl; + inventory.write(reinterpret_cast(&record), + sizeof(record)); + } + + // Close the file. + inventory.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-21.cpp b/SourceCode/Chapter 12/Pr12-21.cpp new file mode 100755 index 0000000..7594394 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-21.cpp @@ -0,0 +1,41 @@ +// This program displays the contents of the inventory file. +#include +#include +using namespace std; + +const int DESC_SIZE = 31; // Description size + +// Declaration of InventoryItem structure +struct InventoryItem +{ + char desc[DESC_SIZE]; + int qty; + double price; +}; + +int main() +{ + InventoryItem record; // To hold an inventory record + + // Open the file for binary input. + fstream inventory("Inventory.dat", ios::in | ios::binary); + + // Now read and display the records. + inventory.read(reinterpret_cast(&record), + sizeof(record)); + while (!inventory.eof()) + { + cout << "Description: "; + cout << record.desc << endl; + cout << "Quantity: "; + cout << record.qty << endl; + cout << "Price: "; + cout << record.price << endl << endl; + inventory.read(reinterpret_cast(&record), + sizeof(record)); + } + + // Close the file. + inventory.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-22.cpp b/SourceCode/Chapter 12/Pr12-22.cpp new file mode 100755 index 0000000..058619c --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-22.cpp @@ -0,0 +1,62 @@ +// This program allows the user to edit a specific record. +#include +#include +using namespace std; + +const int DESC_SIZE = 31; // Description size + +// Declaration of InventoryItem structure +struct InventoryItem +{ + char desc[DESC_SIZE]; + int qty; + double price; +}; + +int main() +{ + InventoryItem record; // To hold an inventory record + long recNum; // To hold a record number + + // Open the file in binary mode for input and output. + fstream inventory("Inventory.dat", + ios::in | ios::out | ios::binary); + + // Get the record number of the desired record. + cout << "Which record do you want to edit? "; + cin >> recNum; + + // Move to the record and read it. + inventory.seekg(recNum * sizeof(record), ios::beg); + inventory.read(reinterpret_cast(&record), + sizeof(record)); + + // Display the record contents. + cout << "Description: "; + cout << record.desc << endl; + cout << "Quantity: "; + cout << record.qty << endl; + cout << "Price: "; + cout << record.price << endl; + + // Get the new record data. + cout << "Enter the new data:\n"; + cout << "Description: "; + cin.ignore(); + cin.getline(record.desc, DESC_SIZE); + cout << "Quantity: "; + cin >> record.qty; + cout << "Price: "; + cin >> record.price; + + // Move back to the beginning of the this record's position. + inventory.seekp(recNum * sizeof(record), ios::beg); + + // Write the new record over the current record. + inventory.write(reinterpret_cast(&record), + sizeof(record)); + + // Close the file. + inventory.close(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-3.cpp b/SourceCode/Chapter 12/Pr12-3.cpp new file mode 100755 index 0000000..30b8ffa --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-3.cpp @@ -0,0 +1,33 @@ +// This program uses the setprecision and fixed +// manipulators to format file output. +#include +#include +#include +using namespace std; + +int main() +{ + fstream dataFile; + double num = 17.816392; + + dataFile.open("numfile.txt", ios::out); // Open in output mode + + dataFile << fixed; // Format for fixed-point notation + dataFile << num << endl; // Write the number + + dataFile << setprecision(4); // Format for 4 decimal places + dataFile << num << endl; // Write the number + + dataFile << setprecision(3); // Format for 3 decimal places + dataFile << num << endl; // Write the number + + dataFile << setprecision(2); // Format for 2 decimal places + dataFile << num << endl; // Write the number + + dataFile << setprecision(1); // Format for 1 decimal place + dataFile << num << endl; // Write the number + + cout << "Done.\n"; + dataFile.close(); // Close the file + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-4.cpp b/SourceCode/Chapter 12/Pr12-4.cpp new file mode 100755 index 0000000..7eaf9bf --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-4.cpp @@ -0,0 +1,29 @@ +// This program writes three rows of numbers to a file. +#include +#include +#include +using namespace std; + +int main() +{ + const int ROWS = 3; // Rows to write + const int COLS = 3; // Columns to write + int nums[ROWS][COLS] = { 2897, 5, 837, + 34, 7, 1623, + 390, 3456, 12 }; + fstream outFile("table.txt", ios::out); + + // Write the three rows of numbers with each + // number in a field of 8 character spaces. + for (int row = 0; row < ROWS; row++) + { + for (int col = 0; col < COLS; col++) + { + outFile << setw(8) << nums[row][col]; + } + outFile << endl; + } + outFile.close(); + cout << "Done.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-5.cpp b/SourceCode/Chapter 12/Pr12-5.cpp new file mode 100755 index 0000000..c38d8cb --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-5.cpp @@ -0,0 +1,60 @@ +// This program demonstrates how file stream objects may +// be passed by reference to functions. +#include +#include +#include +using namespace std; + +// Function prototypes +bool openFileIn(fstream &, string); +void showContents(fstream &); + +int main() +{ + fstream dataFile; + + if (openFileIn(dataFile, "demofile.txt")) + { + cout << "File opened successfully.\n"; + cout << "Now reading data from the file.\n\n"; + showContents(dataFile); + dataFile.close(); + cout << "\nDone.\n"; + } + else + cout << "File open error!" << endl; + + return 0; +} + +//*********************************************************** +// Definition of function openFileIn. Accepts a reference * +// to an fstream object as an argument. The file is opened * +// for input. The function returns true upon success, false * +// upon failure. * +//*********************************************************** + +bool openFileIn(fstream &file, string name) +{ + file.open(name, ios::in); + if (file.fail()) + return false; + else + return true; +} + +//*********************************************************** +// Definition of function showContents. Accepts an fstream * +// reference as its argument. Uses a loop to read each name * +// from the file and displays it on the screen. * +//*********************************************************** + +void showContents(fstream &file) +{ + string line; + + while (file >> line) + { + cout << line << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-6.cpp b/SourceCode/Chapter 12/Pr12-6.cpp new file mode 100755 index 0000000..7a1dc4e --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-6.cpp @@ -0,0 +1,76 @@ +// This program demonstrates the return value of the stream +// object error testing member functions. +#include +#include +using namespace std; + +// Function prototype +void showState(fstream &); + +int main() +{ + int num = 10; + + // Open the file for output. + fstream testFile("stuff.dat", ios::out); + if (testFile.fail()) + { + cout << "ERROR: cannot open the file.\n"; + return 0; + } + + // Write a value to the file. + cout << "Writing the value " << num << " to the file.\n"; + testFile << num; + + // Show the bit states. + showState(testFile); + + // Close the file. + testFile.close(); + + // Reopen the file for input. + testFile.open("stuff.dat", ios::in); + if (testFile.fail()) + { + cout << "ERROR: cannot open the file.\n"; + return 0; + } + + // Read the only value from the file. + cout << "Reading from the file.\n"; + testFile >> num; + cout << "The value " << num << " was read.\n"; + + // Show the bit states. + showState(testFile); + + // No more data in the file, but force an invalid read operation. + cout << "Forcing a bad read operation.\n"; + testFile >> num; + + // Show the bit states. + showState(testFile); + + // Close the file. + testFile.close(); + return 0; +} + +//***************************************************************** +// Definition of function showState. This function uses * +// an fstream reference as its parameter. The return values of * +// the eof(), fail(), bad(), and good() member functions are * +// displayed. The clear() function is called before the function * +// reutrns. * +//***************************************************************** + +void showState(fstream &file) +{ + cout << "File Status:\n"; + cout << " eof bit: " << file.eof() << endl; + cout << " fail bit: " << file.fail() << endl; + cout << " bad bit: " << file.bad() << endl; + cout << " good bit: " << file.good() << endl; + file.clear(); // Clear any bad bits +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-7.cpp b/SourceCode/Chapter 12/Pr12-7.cpp new file mode 100755 index 0000000..144ff11 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-7.cpp @@ -0,0 +1,34 @@ +// This program demonstrates how the >> operator should not +// be used to read data that contain whitespace characters +// from a file. +#include +#include +#include +using namespace std; + +int main() +{ + string input; // To hold file input + fstream nameFile; // File stream object + + // Open the file in input mode. + nameFile.open("murphy.txt", ios::in); + + // If the file was successfully opened, continue. + if (nameFile) + { + // Read the file contents. + while (nameFile >> input) + { + cout << input; + } + + // Close the file. + nameFile.close(); + } + else + { + cout << "ERROR: Cannot open file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-8.cpp b/SourceCode/Chapter 12/Pr12-8.cpp new file mode 100755 index 0000000..ea33e41 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-8.cpp @@ -0,0 +1,41 @@ +// This program uses the getline function to read a line of +// data from the file. +#include +#include +#include +using namespace std; + +int main() +{ + string input; // To hold file input + fstream nameFile; // File stream object + + // Open the file in input mode. + nameFile.open("murphy.txt", ios::in); + + // If the file was successfully opened, continue. + if (nameFile) + { + // Read an item from the file. + getline(nameFile, input); + + // While the last read operation + // was successful, continue. + while (nameFile) + { + // Display the last item read. + cout << input << endl; + + // Read the next item. + getline(nameFile, input); + } + + // Close the file. + nameFile.close(); + } + else + { + cout << "ERROR: Cannot open file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/Pr12-9.cpp b/SourceCode/Chapter 12/Pr12-9.cpp new file mode 100755 index 0000000..7a97991 --- /dev/null +++ b/SourceCode/Chapter 12/Pr12-9.cpp @@ -0,0 +1,40 @@ +// This file demonstrates the getline function with +// a specified delimiter. +#include +#include +#include +using namespace std; + +int main() +{ + string input; // To hold file input + + // Open the file for input. + fstream dataFile("names2.txt", ios::in); + + // If the file was successfully opened, continue. + if (dataFile) + { + // Read an item using $ as a delimiter. + getline(dataFile, input, '$'); + + // While the last read operation + // was successful, continue. + while (dataFile) + { + // Display the last item read. + cout << input << endl; + + // Read an item using $ as a delimiter. + getline(dataFile, input, '$'); + } + + // Close the file. + dataFile.close(); + } + else + { + cout << "ERROR: Cannot open file.\n"; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 12/demofile.txt b/SourceCode/Chapter 12/demofile.txt new file mode 100755 index 0000000..7a19b32 --- /dev/null +++ b/SourceCode/Chapter 12/demofile.txt @@ -0,0 +1,4 @@ +Jones +Smith +Willis +Davis \ No newline at end of file diff --git a/SourceCode/Chapter 12/hownow.txt b/SourceCode/Chapter 12/hownow.txt new file mode 100755 index 0000000..da77d85 --- /dev/null +++ b/SourceCode/Chapter 12/hownow.txt @@ -0,0 +1,2 @@ +how now brown cow. +How Now? \ No newline at end of file diff --git a/SourceCode/Chapter 12/joke.txt b/SourceCode/Chapter 12/joke.txt new file mode 100755 index 0000000..975ff62 --- /dev/null +++ b/SourceCode/Chapter 12/joke.txt @@ -0,0 +1,12 @@ +Two men who work together in a facory were talking. +"I know how to get some time off," said one. +"How are you going to do that?" asked the other. +"Watch," he said, and climbed a ladder to the ceiling. +The foreman asked what he was doing up there, +and the man replied. "I'm a lightbulb." +"I think you need some time off," the foreman +said, and the first man walked out of the +factory. After a moment, the second man followed +him. "Where do you think you're going?" +the foreman shouted. + diff --git a/SourceCode/Chapter 12/letters.txt b/SourceCode/Chapter 12/letters.txt new file mode 100755 index 0000000..e85d5b4 --- /dev/null +++ b/SourceCode/Chapter 12/letters.txt @@ -0,0 +1 @@ +abcdefghijklmnopqrstuvwxyz \ No newline at end of file diff --git a/SourceCode/Chapter 12/murphy.txt b/SourceCode/Chapter 12/murphy.txt new file mode 100755 index 0000000..80ff865 --- /dev/null +++ b/SourceCode/Chapter 12/murphy.txt @@ -0,0 +1,3 @@ +Jayne Murphy +47 Jones Circle +Almond, NC 28702 diff --git a/SourceCode/Chapter 12/names2.txt b/SourceCode/Chapter 12/names2.txt new file mode 100755 index 0000000..57dd377 --- /dev/null +++ b/SourceCode/Chapter 12/names2.txt @@ -0,0 +1,4 @@ +Jayne Murphy$47 Jones Circle$Almond, NC 28702 +$Bobie Smith$217 Halifax Drive$Canton, NC 28716 +$Bill Hammet$PO Box 121$Springfield, NC 28357 +$ \ No newline at end of file diff --git a/SourceCode/Chapter 12/numbers.dat b/SourceCode/Chapter 12/numbers.dat new file mode 100755 index 0000000..dd67d8d Binary files /dev/null and b/SourceCode/Chapter 12/numbers.dat differ diff --git a/SourceCode/Chapter 12/numfile.txt b/SourceCode/Chapter 12/numfile.txt new file mode 100755 index 0000000..09c6352 --- /dev/null +++ b/SourceCode/Chapter 12/numfile.txt @@ -0,0 +1,5 @@ +17.816392 +17.8164 +17.816 +17.82 +17.8 diff --git a/SourceCode/Chapter 12/out.txt b/SourceCode/Chapter 12/out.txt new file mode 100755 index 0000000..e030c33 --- /dev/null +++ b/SourceCode/Chapter 12/out.txt @@ -0,0 +1,2 @@ +HOW NOW BROWN COW. +HOW NOW? \ No newline at end of file diff --git a/SourceCode/Chapter 12/people.dat b/SourceCode/Chapter 12/people.dat new file mode 100755 index 0000000..5ddda54 Binary files /dev/null and b/SourceCode/Chapter 12/people.dat differ diff --git a/SourceCode/Chapter 12/punchline.txt b/SourceCode/Chapter 12/punchline.txt new file mode 100755 index 0000000..d4662f9 --- /dev/null +++ b/SourceCode/Chapter 12/punchline.txt @@ -0,0 +1,4 @@ +asfasdfasdfasdfsdf +asdfasdfsadfsadfsadf +asdfsadfsdfsdf +"I can't work in the dark," he said. \ No newline at end of file diff --git a/SourceCode/Chapter 12/sentence.txt b/SourceCode/Chapter 12/sentence.txt new file mode 100755 index 0000000..66a6aa4 --- /dev/null +++ b/SourceCode/Chapter 12/sentence.txt @@ -0,0 +1 @@ +I am on my way to becoming a great programmer. \ No newline at end of file diff --git a/SourceCode/Chapter 12/stuff.dat b/SourceCode/Chapter 12/stuff.dat new file mode 100755 index 0000000..9a03714 --- /dev/null +++ b/SourceCode/Chapter 12/stuff.dat @@ -0,0 +1 @@ +10 \ No newline at end of file diff --git a/SourceCode/Chapter 12/table.txt b/SourceCode/Chapter 12/table.txt new file mode 100755 index 0000000..e91f701 --- /dev/null +++ b/SourceCode/Chapter 12/table.txt @@ -0,0 +1,3 @@ + 2897 5 837 + 34 7 1623 + 390 3456 12 \ No newline at end of file diff --git a/SourceCode/Chapter 12/test.dat b/SourceCode/Chapter 12/test.dat new file mode 100755 index 0000000..a6bddc4 --- /dev/null +++ b/SourceCode/Chapter 12/test.dat @@ -0,0 +1 @@ +ABCD \ No newline at end of file diff --git a/SourceCode/Chapter 12/text.txt b/SourceCode/Chapter 12/text.txt new file mode 100755 index 0000000..891c93d --- /dev/null +++ b/SourceCode/Chapter 12/text.txt @@ -0,0 +1,10 @@ +No one is unaware of the name of that famous English shipowner, Cunard. +In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons. +Eight years later, the company's assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage. +In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas. +So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers. +If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management. +No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success. +In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost. +Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents. +Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers. \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-1.cpp b/SourceCode/Chapter 16/Pr16-1.cpp new file mode 100755 index 0000000..9d74810 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-1.cpp @@ -0,0 +1,49 @@ +// This program demonstrates an exception being thrown and caught. +#include +#include +using namespace std; + +// Function prototype +double divide(int, int); + +int main() +{ + int num1, num2; // To hold two numbers + double quotient; // To hold the quotient of the numbers + + // Get two numbers. + cout << "Enter two numbers: "; + cin >> num1 >> num2; + + // Divide num1 by num2 and catch any + // potential exceptions. + try + { + quotient = divide(num1, num2); + cout << "The quotient is " << quotient << endl; + } + catch (string exceptionString) + { + cout << exceptionString; + } + + cout << "End of the program.\n"; + return 0; +} + +//******************************************** +// The divide function divides numerator by * +// denominator. If denominator is zero, the * +// function throws an exception. * +//******************************************** + +double divide(int numerator, int denominator) +{ + if (denominator == 0) + { + string exceptionString = "ERROR: Cannot divide by zero.\n"; + throw exceptionString; + } + + return static_cast(numerator) / denominator; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-10.cpp b/SourceCode/Chapter 16/Pr16-10.cpp new file mode 100755 index 0000000..496b444 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-10.cpp @@ -0,0 +1,31 @@ +// This program demonstrates an overloaded function template. +#include +using namespace std; + +template +T sum(T val1, T val2) +{ + return val1 + val2; +} + +template +T sum(T val1, T val2, T val3) +{ + return val1 + val2 + val3; +} + +int main() +{ + double num1, num2, num3; + + // Get two values and display their sum. + cout << "Enter two values: "; + cin >> num1 >> num2; + cout << "Their sum is " << sum(num1, num2) << endl; + + // Get three values and display their sum. + cout << "Enter three values: "; + cin >> num1 >> num2 >> num3; + cout << "Their sum is " << sum(num1, num2, num3) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-11.cpp b/SourceCode/Chapter 16/Pr16-11.cpp new file mode 100755 index 0000000..27fbf49 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-11.cpp @@ -0,0 +1,73 @@ +// This program demonstrates the SimpleVector template. +#include +#include "SimpleVector.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Number of elements + int count; // Loop counter + + // Create a SimpleVector of ints. + SimpleVector intTable(SIZE); + + // Create a SimpleVector of doubles. + SimpleVector doubleTable(SIZE); + + // Store values in the two SimpleVectors. + for (count = 0; count < SIZE; count++) + { + intTable[count] = (count * 2); + doubleTable[count] = (count * 2.14); + } + + // Display the values in the SimpleVectors. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + // Use the standard + operator on the elements. + cout << "\nAdding 5 to each element of intTable" + << " and doubleTable.\n"; + for (count = 0; count < SIZE; count++) + { + intTable[count] = intTable[count] + 5; + doubleTable[count] = doubleTable[count] + 5.0; + } + + // Display the values in the SimpleVectors. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + // Use the standard ++ operator on the elements. + cout << "\nIncrementing each element of intTable and" + << " doubleTable.\n"; + for (count = 0; count < SIZE; count++) + { + intTable[count]++; + doubleTable[count]++; + } + + // Display the values in the SimpleVectors. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-12.cpp b/SourceCode/Chapter 16/Pr16-12.cpp new file mode 100755 index 0000000..5f48d77 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-12.cpp @@ -0,0 +1,49 @@ +// This program demonstrates the SearchableVector template. +#include +#include "SearchableVector.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Number of elements + int count; // Loop counter + int result; // To hold search results + + // Create two SearchableVector objects. + SearchableVector intTable(SIZE); + SearchableVector doubleTable(SIZE); + + // Store values in the objects. + for (count = 0; count < SIZE; count++) + { + intTable[count] = (count * 2); + doubleTable[count] = (count * 2.14); + } + + // Display the values in the objects. + cout << "These values are in intTable:\n"; + for (count = 0; count < SIZE; count++) + cout << intTable[count] << " "; + cout << endl << endl; + cout << "These values are in doubleTable:\n"; + for (count = 0; count < SIZE; count++) + cout << doubleTable[count] << " "; + cout << endl; + + // Search for the value 6 in intTable. + cout << "\nSearching for 6 in intTable.\n"; + result = intTable.findItem(6); + if (result == -1) + cout << "6 was not found in intTable.\n"; + else + cout << "6 was found at subscript " << result << endl; + + // Search for the value 12.84 in doubleTable. + cout << "\nSearching for 12.84 in doubleTable.\n"; + result = doubleTable.findItem(12.84); + if (result == -1) + cout << "12.84 was not found in doubleTable.\n"; + else + cout << "12.84 was found at subscript " << result << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-13.cpp b/SourceCode/Chapter 16/Pr16-13.cpp new file mode 100755 index 0000000..d50f009 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-13.cpp @@ -0,0 +1,40 @@ +// This program provides a simple demonstration of the +// vector STL template. +#include +#include // Include the vector header +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a vector object. + vector vect; + + // Use the size member function to get + // the number of elements in the vector. + cout << "vect starts with " << vect.size() + << " elements.\n"; + + // Use push_back to push values into the vector. + for (count = 0; count < 10; count++) + vect.push_back(count); + + // Display the size of the vector now. + cout << "Now vect has " << vect.size() + << " elements. Here they are:\n"; + + // Use the [] operator to display each element. + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Use the pop_back member function. + cout << "Popping the values out of vect...\n"; + for (count = 0; count < 10; count++) + vect.pop_back(); + + // Display the size of the vector now. + cout << "Now vect has " << vect.size() << " elements.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-14.cpp b/SourceCode/Chapter 16/Pr16-14.cpp new file mode 100755 index 0000000..856c941 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-14.cpp @@ -0,0 +1,35 @@ +// This program provides a simple iterator demonstration. +#include +#include // Include the vector header +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a vector object + vector vect; + + // Define an iterator object + vector::iterator iter; + + // Use push_back to push values into the vector. + for (count = 0; count < 10; count++) + vect.push_back(count); + + // Step the iterator through the vector, + // and use it to display the vector's contents. + cout << "Here are the values in vect: "; + for (iter = vect.begin(); iter < vect.end(); iter++) + { + cout << *iter << " "; + } + + // Step the iterator through the vector backwards. + cout << "\nand here they are backwards: "; + for (iter = vect.end() - 1; iter >= vect.begin(); iter--) + { + cout << *iter << " "; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-15.cpp b/SourceCode/Chapter 16/Pr16-15.cpp new file mode 100755 index 0000000..d802f1f --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-15.cpp @@ -0,0 +1,49 @@ +// A simple demonstration of STL algorithms +#include +#include // Required for the vector type +#include // Required for STL algorithms +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a vector object. + vector vect; + + // Use push_back to push values into the vector. + for (count = 0; count < 10; count++) + vect.push_back(count); + + // Display the vector's elements. + cout << "The vector has " << vect.size() + << " elements. Here they are:\n"; + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Randomly shuffle the vector's contents. + random_shuffle(vect.begin(), vect.end()); + + // Display the vector's elements. + cout << "The elements have been shuffled:\n"; + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Now sort the vector's elements. + sort(vect.begin(), vect.end()); + + // Display the vector's elements again. + cout << "The elements have been sorted:\n"; + for (count = 0; count < vect.size(); count++) + cout << vect[count] << " "; + cout << endl; + + // Now search for an element with the value 7. + if (binary_search(vect.begin(), vect.end(), 7)) + cout << "The value 7 was found in the vector.\n"; + else + cout << "The value 7 was not found in the vector.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-16.cpp b/SourceCode/Chapter 16/Pr16-16.cpp new file mode 100755 index 0000000..1222533 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-16.cpp @@ -0,0 +1,37 @@ +// This program demonstrates the STL count algorithm. +#include +#include // Needed to define the vector +#include // Needed for the count algorithm +using namespace std; + +int main() +{ + // Define a vector object. + vector values; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some values in the vector. + values.push_back(1); + values.push_back(2); + values.push_back(2); + values.push_back(3); + values.push_back(3); + values.push_back(3); + + // Display the values in the vector. + cout << "The values in the vector are:\n"; + for (iter = values.begin(); iter < values.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Display the count of each number. + cout << "The number of 1s in the vector is "; + cout << count(values.begin(), values.end(), 1) << endl; + cout << "The number of 2s in the vector is "; + cout << count(values.begin(), values.end(), 2) << endl; + cout << "The number of 3s in the vector is "; + cout << count(values.begin(), values.end(), 3) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-17.cpp b/SourceCode/Chapter 16/Pr16-17.cpp new file mode 100755 index 0000000..04b19f2 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-17.cpp @@ -0,0 +1,33 @@ +// A demonstration of the max_element and min_element algorithms +#include +#include // Needed to define the vector +#include // Needed for the algorithms +using namespace std; + +int main() +{ + // Define a vector object. + vector numbers; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some numbers in the vector. + for (int count = 0; count < 10; count++) + numbers.push_back(count); + + // Display the numbers in the vector. + cout << "The numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Find the largest value in the vector. + iter = max_element(numbers.begin(), numbers.end()); + cout << "The largest value in the vector is " << *iter << endl; + + // Find the smallest value in the vector. + iter = min_element(numbers.begin(), numbers.end()); + cout << "The smallest value in the vector is " << *iter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-18.cpp b/SourceCode/Chapter 16/Pr16-18.cpp new file mode 100755 index 0000000..a473e7d --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-18.cpp @@ -0,0 +1,29 @@ +// A demonstration of the STL find algorithm. +#include +#include // Needed to define the vector +#include // Needed for the find algorithm +using namespace std; + +int main() +{ + // Define a vector object. + vector numbers; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some numbers in the vector. + for (int x = 0; x < 10; x++) + numbers.push_back(x); + + // Display the numbers in the vector. + cout << "The numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Find the number 7 in the vector. + iter = find(numbers.begin(), numbers.end(), 7); + cout << *iter << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-19.cpp b/SourceCode/Chapter 16/Pr16-19.cpp new file mode 100755 index 0000000..96cceb6 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-19.cpp @@ -0,0 +1,48 @@ +// A demonstration of the for_each find algorithm. +#include +#include // Needed to define the vector +#include // Needed for the for_each algorithm +using namespace std; + +// Function prototype +void doubleValue(int &); + +int main() +{ + // Define a vector object. + vector numbers; + + // Define an iterator for the vector. + vector::iterator iter; + + // Store some numbers in the vector. + for (int x = 0; x < 10; x++) + numbers.push_back(x); + + // Display the numbers in the vector. + cout << "The numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl << endl; + + // Double the values in the vector. + for_each(numbers.begin(), numbers.end(), doubleValue); + + // Display the numbers in the vector again + cout << "Now the numbers in the vector are:\n"; + for (iter = numbers.begin(); iter != numbers.end(); iter++) + cout << *iter << " "; + cout << endl; + return 0; +} + +//******************************************************** +// Function doubleValue. This function accepts an int * +// reference as its argument. The value of the argument * +// is doubled. * +//******************************************************** + +void doubleValue(int &val) +{ + val *= 2; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-6.cpp b/SourceCode/Chapter 16/Pr16-6.cpp new file mode 100755 index 0000000..513f355 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-6.cpp @@ -0,0 +1,20 @@ +// This program demonstrates the bad_alloc exception. +#include +#include // Needed for bad_alloc +using namespace std; + +int main() +{ + double *ptr = nullptr; // Pointer to double + + try + { + ptr = new double [10000]; + } + catch (bad_alloc) + { + cout << "Insufficient memory.\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-7.cpp b/SourceCode/Chapter 16/Pr16-7.cpp new file mode 100755 index 0000000..8292ee6 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-7.cpp @@ -0,0 +1,25 @@ +// This program uses a function template. +#include +#include +using namespace std; + +// Template definition for square function. +template +T square(T number) +{ + return number * number; +} + +int main() +{ + int userInt; // To hold integer input + double userDouble; // To hold double input + + cout << setprecision(5); + cout << "Enter an integer and a floating-point value: "; + cin >> userInt >> userDouble; + cout << "Here are their squares: "; + cout << square(userInt) << " and " + << square(userDouble) << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-8.cpp b/SourceCode/Chapter 16/Pr16-8.cpp new file mode 100755 index 0000000..6600d7f --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-8.cpp @@ -0,0 +1,39 @@ +// This program demonstrates the swapVars function template. +#include +using namespace std; + +template +void swapVars(T &var1, T &var2) +{ + T temp; + + temp = var1; + var1 = var2; + var2 = temp; +} + +int main() +{ + char firstChar, secondChar; // Two chars + int firstInt, secondInt; // Two ints + double firstDouble, secondDouble; // Two doubles + + // Get and swapVars two chars + cout << "Enter two characters: "; + cin >> firstChar >> secondChar; + swapVars(firstChar, secondChar); + cout << firstChar << " " << secondChar << endl; + + // Get and swapVars two ints + cout << "Enter two integers: "; + cin >> firstInt >> secondInt; + swapVars(firstInt, secondInt); + cout << firstInt << " " << secondInt << endl; + + // Get and swapVars two doubles + cout << "Enter two floating-point numbers: "; + cin >> firstDouble >> secondDouble; + swapVars(firstDouble, secondDouble); + cout << firstDouble << " " << secondDouble << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Pr16-9.cpp b/SourceCode/Chapter 16/Pr16-9.cpp new file mode 100755 index 0000000..cb18149 --- /dev/null +++ b/SourceCode/Chapter 16/Pr16-9.cpp @@ -0,0 +1,29 @@ +// This program demonstrates a function template +// with two type parameters. +#include +using namespace std; + +template +int largest(const T1 &var1, T2 &var2) +{ + if (sizeof(var1) > sizeof(var2)) + return sizeof(var1); + else + return sizeof(var2); +} + +int main() +{ + int i = 0; + char c = ' '; + float f = 0.0; + double d = 0.0; + + cout << "Comparing an int and a double, the largest\n" + << "of the two is " << largest(i, d) << " bytes.\n"; + + cout << "Comparing an char and a float, the largest\n" + << "of the two is " << largest(c, f) << " bytes.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 1/Pr16-2.cpp b/SourceCode/Chapter 16/Rectangle Version 1/Pr16-2.cpp new file mode 100755 index 0000000..fcc8b11 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 1/Pr16-2.cpp @@ -0,0 +1,35 @@ +// This program demonstrates Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; + int length; + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the width and length. + cout << "Enter the rectangle's width: "; + cin >> width; + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store these values in the Rectangle object. + try + { + myRectangle.setWidth(width); + myRectangle.setLength(length); + cout << "The area of the rectangle is " + << myRectangle.getArea() << endl; + } + catch (Rectangle::NegativeSize) + { + cout << "Error: A negative value was entered.\n"; + } + cout << "End of the program.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.cpp b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.cpp new file mode 100755 index 0000000..18c5a1b --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.cpp @@ -0,0 +1,26 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + throw NegativeSize(); +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + throw NegativeSize(); +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.h b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.h new file mode 100755 index 0000000..35f695f --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 1/Rectangle.h @@ -0,0 +1,33 @@ +// Specification file for the Rectangle class +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; // The rectangle's width + double length; // The rectangle's length + public: + // Exception class + class NegativeSize + { }; // Empty class declaration + + // Default constructor + Rectangle() + { width = 0.0; length = 0.0; } + + // Mutator functions, defined in Rectangle.cpp + void setWidth(double); + void setLength(double); + + // Accessor functions + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Pr16-3.cpp b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-3.cpp new file mode 100755 index 0000000..b81a541 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-3.cpp @@ -0,0 +1,41 @@ +// This program demonstrates Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; + int length; + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the width and length. + cout << "Enter the rectangle's width: "; + cin >> width; + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store these values in the Rectangle object. + try + { + myRectangle.setWidth(width); + myRectangle.setLength(length); + cout << "The area of the rectangle is " + << myRectangle.getArea() << endl; + } + catch (Rectangle::NegativeWidth) + { + cout << "Error: A negative value was given " + << "for the rectangle's width.\n"; + } + catch (Rectangle::NegativeLength) + { + cout << "Error: A negative value was given " + << "for the rectangle's length.\n"; + } + + cout << "End of the program.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Pr16-4.cpp b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-4.cpp new file mode 100755 index 0000000..e69d5a1 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Pr16-4.cpp @@ -0,0 +1,62 @@ +// This program handles the Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; // Rectangle's width + int length; // Rectangle's length + bool tryAgain = true; // Flag to re-read input + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the rectangle's width. + cout << "Enter the rectangle's width: "; + cin >> width; + + // Store the width in the myRectangle object. + while (tryAgain) + { + try + { + myRectangle.setWidth(width); + // If no exception was thrown, then the + // next statement will execute. + tryAgain = false; + } + catch (Rectangle::NegativeWidth) + { + cout << "Please enter a non-negative value: "; + cin >> width; + } + } + + // Get the rectangle's length. + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store the length in the myRectangle object. + tryAgain = true; + while (tryAgain) + { + try + { + myRectangle.setLength(length); + // If no exception was thrown, then the + // next statement will execute. + tryAgain = false; + } + catch (Rectangle::NegativeLength) + { + cout << "Please enter a non-negative value: "; + cin >> length; + } + } + + // Display the area of the rectangle. + cout << "The rectangle's area is " + << myRectangle.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.cpp b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.cpp new file mode 100755 index 0000000..4c0ed1f --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.cpp @@ -0,0 +1,26 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + throw NegativeWidth(); +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + throw NegativeLength(); +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.h b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.h new file mode 100755 index 0000000..0744be5 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 2/Rectangle.h @@ -0,0 +1,37 @@ +// Specification file for the Rectangle class +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; // The rectangle's width + double length; // The rectangle's length + public: + // Exception class for a negative width + class NegativeWidth + { }; + + // Exception class for a negative length + class NegativeLength + { }; + + // Default constructor + Rectangle() + { width = 0.0; length = 0.0; } + + // Mutator functions, defined in Rectangle.cpp + void setWidth(double); + void setLength(double); + + // Accessor functions + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 3/Pr16-5.cpp b/SourceCode/Chapter 16/Rectangle Version 3/Pr16-5.cpp new file mode 100755 index 0000000..e14dad2 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 3/Pr16-5.cpp @@ -0,0 +1,43 @@ +// This program demonstrates Rectangle class exceptions. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + int width; + int length; + + // Create a Rectangle object. + Rectangle myRectangle; + + // Get the width and length. + cout << "Enter the rectangle's width: "; + cin >> width; + cout << "Enter the rectangle's length: "; + cin >> length; + + // Store these values in the Rectangle object. + try + { + myRectangle.setWidth(width); + myRectangle.setLength(length); + cout << "The area of the rectangle is " + << myRectangle.getArea() << endl; + } + catch (Rectangle::NegativeWidth e) + { + cout << "Error: " << e.getValue() + << " is an invalid value for the" + << " rectangle's width.\n"; + } + catch (Rectangle::NegativeLength e) + { + cout << "Error: " << e.getValue() + << " is an invalid value for the" + << " rectangle's length.\n"; + } + + cout << "End of the program.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.cpp b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.cpp new file mode 100755 index 0000000..7e8cbf1 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.cpp @@ -0,0 +1,26 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + throw NegativeWidth(w); +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + throw NegativeLength(len); +} \ No newline at end of file diff --git a/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.h b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.h new file mode 100755 index 0000000..04112d5 --- /dev/null +++ b/SourceCode/Chapter 16/Rectangle Version 3/Rectangle.h @@ -0,0 +1,55 @@ +// Specification file for the Rectangle class +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; // The rectangle's width + double length; // The rectangle's length + public: + // Exception class for a negative width + class NegativeWidth + { + private: + int value; + public: + NegativeWidth(int val) + { value = val; } + + int getValue() const + { return value; } + }; + + // Exception class for a negative length + class NegativeLength + { + private: + int value; + public: + NegativeLength(int val) + { value = val; } + + int getValue() const + { return value; } + }; + + // Default constructor + Rectangle() + { width = 0.0; length = 0.0; } + + // Mutator functions, defined in Rectangle.cpp + void setWidth(double); + void setLength(double); + + // Accessor functions + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/SearchableVector.h b/SourceCode/Chapter 16/SearchableVector.h new file mode 100755 index 0000000..a1b604f --- /dev/null +++ b/SourceCode/Chapter 16/SearchableVector.h @@ -0,0 +1,52 @@ +#ifndef SEARCHABLEVECTOR_H +#define SEARCHABLEVECTOR_H +#include "SimpleVector.h" + +template +class SearchableVector : public SimpleVector +{ +public: + // Default constructor + SearchableVector() : SimpleVector() + {} + + // Constructor + SearchableVector(int size) : SimpleVector(size) + { } + + // Copy constructor + SearchableVector(const SearchableVector &); + + // Accessor to find an item + int findItem(const T); +}; + +//******************************************************* +// Copy constructor * +//******************************************************* + +template +SearchableVector::SearchableVector(const SearchableVector &obj) : + SimpleVector(obj.size()) +{ + for(int count = 0; count < this->size(); count++) + this->operator[](count) = obj[count]; +} + +//******************************************************* +// findItem function * +// This function searches for item. If item is found * +// the subscript is returned. Otherwise -1 is returned. * +//******************************************************* + +template +int SearchableVector::findItem(const T item) +{ + for (int count = 0; count <= this->size(); count++) + { + if (getElementAt(count) == item) + return count; + } + return -1; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 16/SimpleVector.h b/SourceCode/Chapter 16/SimpleVector.h new file mode 100755 index 0000000..1dbee2d --- /dev/null +++ b/SourceCode/Chapter 16/SimpleVector.h @@ -0,0 +1,149 @@ +// SimpleVector class template +#ifndef SIMPLEVECTOR_H +#define SIMPLEVECTOR_H +#include +#include // Needed for bad_alloc exception +#include // Needed for the exit function +using namespace std; + +template +class SimpleVector +{ +private: + T *aptr; // To point to the allocated array + int arraySize; // Number of elements in the array + void memError(); // Handles memory allocation errors + void subError(); // Handles subscripts out of range + +public: + // Default constructor + SimpleVector() + { aptr = 0; arraySize = 0;} + + // Constructor declaration + SimpleVector(int); + + // Copy constructor declaration + SimpleVector(const SimpleVector &); + + // Destructor declaration + ~SimpleVector(); + + // Accessor to return the array size + int size() const + { return arraySize; } + + // Accessor to return a specific element + T getElementAt(int position); + + // Overloaded [] operator declaration + T &operator[](const int &); +}; + +//*********************************************************** +// Constructor for SimpleVector class. Sets the size of the * +// array and allocates memory for it. * +//*********************************************************** + +template +SimpleVector::SimpleVector(int s) +{ + arraySize = s; + // Allocate memory for the array. + try + { + aptr = new T [s]; + } + catch (bad_alloc) + { + memError(); + } + + // Initialize the array. + for (int count = 0; count < arraySize; count++) + *(aptr + count) = 0; +} + +//******************************************* +// Copy Constructor for SimpleVector class. * +//******************************************* + +template +SimpleVector::SimpleVector(const SimpleVector &obj) +{ + // Copy the array size. + arraySize = obj.arraySize; + + // Allocate memory for the array. + aptr = new T [arraySize]; + if (aptr == 0) + memError(); + + // Copy the elements of obj's array. + for(int count = 0; count < arraySize; count++) + *(aptr + count) = *(obj.aptr + count); +} + +//************************************** +// Destructor for SimpleVector class. * +//************************************** + +template +SimpleVector::~SimpleVector() +{ + if (arraySize > 0) + delete [] aptr; +} + +//******************************************************* +// memError function. Displays an error message and * +// terminates the program when memory allocation fails. * +//******************************************************* + +template +void SimpleVector::memError() +{ + cout << "ERROR:Cannot allocate memory.\n"; + exit(EXIT_FAILURE); +} + +//*********************************************************** +// subError function. Displays an error message and * +// terminates the program when a subscript is out of range. * +//*********************************************************** + +template +void SimpleVector::subError() +{ + cout << "ERROR: Subscript out of range.\n"; + exit(EXIT_FAILURE); +} + +//******************************************************* +// getElementAt function. The argument is a subscript. * +// This function returns the value stored at the sub- * +// cript in the array. * +//******************************************************* + +template +T SimpleVector::getElementAt(int sub) +{ + if (sub < 0 || sub >= arraySize) + subError(); + return aptr[sub]; +} + +//******************************************************* +// Overloaded [] operator. The argument is a subscript. * +// This function returns a reference to the element * +// in the array indexed by the subscript. * +//******************************************************* + +template +T &SimpleVector::operator[](const int &sub) +{ + if (sub < 0 || sub >= arraySize) + subError(); + return aptr[sub]; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.cpp b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.cpp new file mode 100755 index 0000000..9f327c1 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.cpp @@ -0,0 +1,210 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded != operator. Returns true if the current object * +// is set to a value NOT equal to that of right. * +//************************************************************* + +bool FeetInches::operator != (const FeetInches &right) +{ + bool status; + + if (!operator==(right)) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to a double. * +//************************************************************* + +FeetInches::operator double() +{ + double temp = feet; + + temp += (inches / 12.0); + return temp; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to an int. * +//************************************************************* + +FeetInches:: operator int() +{ + return feet; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.h b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.h new file mode 100755 index 0000000..f18a62a --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/FeetInches.h @@ -0,0 +1,64 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + bool operator != (const FeetInches &); // Overloaded == + + // Conversion functions + operator double(); + operator int(); + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/LinkedList.h b/SourceCode/Chapter 17/LinkedList Template Version 1/LinkedList.h new file mode 100755 index 0000000..867717f --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/LinkedList.h @@ -0,0 +1,223 @@ +// A class template for holding a linked list. +#ifndef LINKEDLIST_H +#define LINKEDLIST_H +#include // For cout +using namespace std; + +template +class LinkedList +{ +private: + // Declare a structure for the list + struct ListNode + { + T value; // The value in this node + struct ListNode *next; // To point to the next node + }; + + ListNode *head; // List head pointer + +public: + // Constructor + LinkedList() + { head = nullptr; } + + // Destructor + ~LinkedList(); + + // Linked list operations + void appendNode(T); + void insertNode(T); + void deleteNode(T); + void displayList() const; +}; + + +//************************************************** +// appendNode appends a node containing the value * +// pased into newValue, to the end of the list. * +//************************************************** + +template +void LinkedList::appendNode(T newValue) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store newValue there. + newNode = new ListNode; + newNode->value = newValue; + newNode->next = nullptr; + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value * +// stored in each node of the linked list * +// pointed to by head. * +//************************************************** + +template +void LinkedList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// newValue copied to its value member. * +//************************************************** + +template +void LinkedList::insertNode(T newValue) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store newValue there. + newNode = new ListNode; + newNode->value = newValue; + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than newValue. + while (nodePtr != nullptr && nodePtr->value < newValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//***************************************************** +// The deleteNode function searches for a node * +// with searchValue as its value. The node, if found, * +// is deleted from the list and from memory. * +//***************************************************** + +template +void LinkedList::deleteNode(T searchValue) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == searchValue) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != searchValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +template +LinkedList::~LinkedList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 1/Pr17-5.cpp b/SourceCode/Chapter 17/LinkedList Template Version 1/Pr17-5.cpp new file mode 100755 index 0000000..e955ec7 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 1/Pr17-5.cpp @@ -0,0 +1,46 @@ +// This program demonstrates the linked list template. +#include +#include "LinkedList.h" +#include "FeetInches.h" +using namespace std; + +int main() +{ + // Define a LinkedList object. + LinkedList list; + + // Define some FeetInches objects. + FeetInches distance1(5, 4); // 5 feet 4 inches + FeetInches distance2(6, 8); // 6 feet 8 inches + FeetInches distance3(8, 9); // 8 feet 9 inches + + // Store the FeetInches objects in the list. + list.appendNode(distance1); // 5 feet 4 inches + list.appendNode(distance2); // 6 feet 8 inches + list.appendNode(distance3); // 8 feet 9 inches + + // Display the values in the list. + cout << "Here are the initial values:\n"; + list.displayList(); + cout << endl; + + // Insert another FeetInches object. + cout << "Now inserting the value 7 feet 2 inches.\n"; + FeetInches distance4(7, 2); + list.insertNode(distance4); + + // Display the values in the list. + cout << "Here are the nodes now.\n"; + list.displayList(); + cout << endl; + + // Delete the last node. + cout << "Now deleting the last node.\n"; + FeetInches distance5(8, 9); + list.deleteNode(distance5); + + // Display the values in the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.cpp b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.cpp new file mode 100755 index 0000000..9f327c1 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.cpp @@ -0,0 +1,210 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded != operator. Returns true if the current object * +// is set to a value NOT equal to that of right. * +//************************************************************* + +bool FeetInches::operator != (const FeetInches &right) +{ + bool status; + + if (!operator==(right)) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to a double. * +//************************************************************* + +FeetInches::operator double() +{ + double temp = feet; + + temp += (inches / 12.0); + return temp; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to an int. * +//************************************************************* + +FeetInches:: operator int() +{ + return feet; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.h b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.h new file mode 100755 index 0000000..f18a62a --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/FeetInches.h @@ -0,0 +1,64 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + bool operator != (const FeetInches &); // Overloaded == + + // Conversion functions + operator double(); + operator int(); + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/LinkedList.h b/SourceCode/Chapter 17/LinkedList Template Version 2/LinkedList.h new file mode 100755 index 0000000..38ed3d9 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/LinkedList.h @@ -0,0 +1,233 @@ +// A class template for holding a linked list. +// The node type is also a class template. +#ifndef LINKEDLIST_H +#define LINKEDLIST_H + +//********************************************* +// The ListNode class creates a type used to * +// store a node of the linked list. * +//********************************************* + +template +class ListNode +{ +public: + T value; // Node value + ListNode *next; // Pointer to the next node + + // Constructor + ListNode (T nodeValue) + { value = nodeValue; + next = nullptr;} +}; + +//********************************************* +// LinkedList class * +//********************************************* + +template +class LinkedList +{ +private: + ListNode *head; // List head pointer + +public: + // Constructor + LinkedList() + { head = nullptr; } + + // Destructor + ~LinkedList(); + + // Linked list operations + void appendNode(T); + void insertNode(T); + void deleteNode(T); + void displayList() const; +}; + + +//************************************************** +// appendNode appends a node containing the value * +// pased into newValue, to the end of the list. * +//************************************************** + +template +void LinkedList::appendNode(T newValue) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store newValue there. + newNode = new ListNode(newValue); + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value stored in each node * +// of the linked list pointed to by head. * +//************************************************** + +template +void LinkedList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// newValue copied to its value member. * +//************************************************** + +template +void LinkedList::insertNode(T newValue) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store newValue there. + newNode = new ListNode(newValue); + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than newValue. + while (nodePtr != nullptr && nodePtr->value < newValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//***************************************************** +// The deleteNode function searches for a node * +// with searchValue as its value. The node, if found, * +// is deleted from the list and from memory. * +//***************************************************** + +template +void LinkedList::deleteNode(T searchValue) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == searchValue) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != searchValue) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +template +LinkedList::~LinkedList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/LinkedList Template Version 2/Pr17-5.cpp b/SourceCode/Chapter 17/LinkedList Template Version 2/Pr17-5.cpp new file mode 100755 index 0000000..e955ec7 --- /dev/null +++ b/SourceCode/Chapter 17/LinkedList Template Version 2/Pr17-5.cpp @@ -0,0 +1,46 @@ +// This program demonstrates the linked list template. +#include +#include "LinkedList.h" +#include "FeetInches.h" +using namespace std; + +int main() +{ + // Define a LinkedList object. + LinkedList list; + + // Define some FeetInches objects. + FeetInches distance1(5, 4); // 5 feet 4 inches + FeetInches distance2(6, 8); // 6 feet 8 inches + FeetInches distance3(8, 9); // 8 feet 9 inches + + // Store the FeetInches objects in the list. + list.appendNode(distance1); // 5 feet 4 inches + list.appendNode(distance2); // 6 feet 8 inches + list.appendNode(distance3); // 8 feet 9 inches + + // Display the values in the list. + cout << "Here are the initial values:\n"; + list.displayList(); + cout << endl; + + // Insert another FeetInches object. + cout << "Now inserting the value 7 feet 2 inches.\n"; + FeetInches distance4(7, 2); + list.insertNode(distance4); + + // Display the values in the list. + cout << "Here are the nodes now.\n"; + list.displayList(); + cout << endl; + + // Delete the last node. + cout << "Now deleting the last node.\n"; + FeetInches distance5(8, 9); + list.deleteNode(distance5); + + // Display the values in the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/NumberList.cpp b/SourceCode/Chapter 17/NumberList.cpp new file mode 100755 index 0000000..5f3b55f --- /dev/null +++ b/SourceCode/Chapter 17/NumberList.cpp @@ -0,0 +1,187 @@ +// Implementation file for the NumberList class +#include // For cout +#include "NumberList.h" +using namespace std; + +//************************************************** +// appendNode appends a node containing the * +// value pased into num, to the end of the list. * +//************************************************** + +void NumberList::appendNode(double num) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + newNode->next = nullptr; + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value * +// stored in each node of the linked list * +// pointed to by head. * +//************************************************** + +void NumberList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// num copied to its value member. * +//************************************************** + +void NumberList::insertNode(double num) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than num. + while (nodePtr != nullptr && nodePtr->value < num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//************************************************** +// The deleteNode function searches for a node * +// with num as its value. The node, if found, is * +// deleted from the list and from memory. * +//************************************************** + +void NumberList::deleteNode(double num) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == num) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +NumberList::~NumberList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/NumberList.h b/SourceCode/Chapter 17/NumberList.h new file mode 100755 index 0000000..c42f50c --- /dev/null +++ b/SourceCode/Chapter 17/NumberList.h @@ -0,0 +1,31 @@ +// Specification file for the NumberList class +#ifndef NUMBERLIST_H +#define NUMBERLIST_H + +class NumberList +{ +private: + // Declare a structure for the list + struct ListNode + { + double value; // The value in this node + struct ListNode *next; // To point to the next node + }; + + ListNode *head; // List head pointer + +public: + // Constructor + NumberList() + { head = nullptr; } + + // Destructor + ~NumberList(); + + // Linked list operations + void appendNode(double); + void insertNode(double); + void deleteNode(double); + void displayList() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-1.cpp b/SourceCode/Chapter 17/Pr17-1.cpp new file mode 100755 index 0000000..fe34be2 --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-1.cpp @@ -0,0 +1,17 @@ +// This program demonstrates a simple append +// operation on a linked list. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Append some values to the list. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-2.cpp b/SourceCode/Chapter 17/Pr17-2.cpp new file mode 100755 index 0000000..95db4c8 --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-2.cpp @@ -0,0 +1,19 @@ +// This program demonstrates the displayList member function. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Append some values to the list. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + + // Display the values in the list. + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-3.cpp b/SourceCode/Chapter 17/Pr17-3.cpp new file mode 100755 index 0000000..4e0e957 --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-3.cpp @@ -0,0 +1,22 @@ +// This program demonstrates the insertNode member function. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Build the list with some values. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + + // Insert a node in the middle of the list. + list.insertNode(10.5); + + // Dispay the list + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-4.cpp b/SourceCode/Chapter 17/Pr17-4.cpp new file mode 100755 index 0000000..56200aa --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-4.cpp @@ -0,0 +1,47 @@ +// This program demonstrates the deleteNode member function. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + // Define a NumberList object. + NumberList list; + + // Build the list with some values. + list.appendNode(2.5); + list.appendNode(7.9); + list.appendNode(12.6); + + // Display the list. + cout << "Here are the initial values:\n"; + list.displayList(); + cout << endl; + + // Delete the middle node. + cout << "Now deleting the node in the middle.\n"; + list.deleteNode(7.9); + + // Display the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + cout << endl; + + // Delete the last node. + cout << "Now deleting the last node.\n"; + list.deleteNode(12.6); + + // Display the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + cout << endl; + + // Delete the only node left in the list. + cout << "Now deleting the only remaining node.\n"; + list.deleteNode(2.5); + + // Display the list. + cout << "Here are the nodes left.\n"; + list.displayList(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 17/Pr17-6.cpp b/SourceCode/Chapter 17/Pr17-6.cpp new file mode 100755 index 0000000..de6904b --- /dev/null +++ b/SourceCode/Chapter 17/Pr17-6.cpp @@ -0,0 +1,31 @@ +// This program demonstrates the STL list container. +#include +#include // Include the list header +using namespace std; + +int main() +{ + // Define a list object. + list myList; + + // Define an iterator for the list. + list::iterator iter; + + // Add values to the list + for (int x = 0; x < 100; x += 10) + myList.push_back(x); + + // Display the values + for (iter = myList.begin(); iter != myList.end(); iter++) + cout << *iter << " "; + cout << endl; + + // Now reverse the order of the elements + myList.reverse(); + + // Display the values again + for (iter = myList.begin(); iter != myList.end(); iter++) + cout << *iter << " "; + cout << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntQueue.cpp b/SourceCode/Chapter 18/DynIntQueue.cpp new file mode 100755 index 0000000..c0a08f7 --- /dev/null +++ b/SourceCode/Chapter 18/DynIntQueue.cpp @@ -0,0 +1,110 @@ +#include +#include "DynIntQueue.h" +using namespace std; + +//******************************************** +// The constructor creates an empty queue. * +//******************************************** + +DynIntQueue::DynIntQueue() +{ + front = nullptr; + rear = nullptr; + numItems = 0; +} + +//******************************************** +// Destructor * +//******************************************** + +DynIntQueue::~DynIntQueue() +{ + clear(); +} + +//******************************************** +// Function enqueue inserts the value in num * +// at the rear of the queue. * +//******************************************** + +void DynIntQueue::enqueue(int num) +{ + QueueNode *newNode = nullptr; + + // Create a new node and store num there. + newNode = new QueueNode; + newNode->value = num; + newNode->next = nullptr; + + // Adjust front and rear as necessary. + if (isEmpty()) + { + front = newNode; + rear = newNode; + } + else + { + rear->next = newNode; + rear = newNode; + } + + // Update numItems. + numItems++; +} + +//********************************************** +// Function dequeue removes the value at the * +// front of the queue, and copies it into num. * +//********************************************** + +void DynIntQueue::dequeue(int &num) +{ + QueueNode *temp = nullptr; + + if (isEmpty()) + { + cout << "The queue is empty.\n"; + } + else + { + // Save the front node value in num. + num = front->value; + + // Remove the front node and delete it. + temp = front; + front = front->next; + delete temp; + + // Update numItems. + numItems--; + } +} + +//********************************************* +// Function isEmpty returns true if the queue * +// is empty, and false otherwise. * +//********************************************* + +bool DynIntQueue::isEmpty() const +{ + bool status; + + if (numItems > 0) + status = false; + else + status = true; + return status; +} + +//******************************************** +// Function clear dequeues all the elements * +// in the queue. * +//******************************************** + +void DynIntQueue::clear() +{ + int value; // Dummy variable for dequeue + + while(!isEmpty()) + dequeue(value); +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntQueue.h b/SourceCode/Chapter 18/DynIntQueue.h new file mode 100755 index 0000000..0a60b26 --- /dev/null +++ b/SourceCode/Chapter 18/DynIntQueue.h @@ -0,0 +1,31 @@ +#ifndef DYNINTQUEUE_H +#define DYNINTQUEUE_H + +class DynIntQueue +{ +private: + // Structure for the queue nodes + struct QueueNode + { + int value; // Value in a node + QueueNode *next; // Pointer to the next node + }; + + QueueNode *front; // The front of the queue + QueueNode *rear; // The rear of the queue + int numItems; // Number of items in the queue +public: + // Constructor + DynIntQueue(); + + // Destructor + ~DynIntQueue(); + + // Queue operations + void enqueue(int); + void dequeue(int &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntStack.cpp b/SourceCode/Chapter 18/DynIntStack.cpp new file mode 100755 index 0000000..930ae65 --- /dev/null +++ b/SourceCode/Chapter 18/DynIntStack.cpp @@ -0,0 +1,92 @@ +#include +#include "DynIntStack.h" +using namespace std; + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +DynIntStack::~DynIntStack() +{ + StackNode *nodePtr = nullptr, *nextNode = nullptr; + + // Position nodePtr at the top of the stack. + nodePtr = top; + + // Traverse the list deleting each node. + while (nodePtr != nullptr) + { + nextNode = nodePtr->next; + delete nodePtr; + nodePtr = nextNode; + } +} + +//************************************************ +// Member function push pushes the argument onto * +// the stack. * +//************************************************ + +void DynIntStack::push(int num) +{ + StackNode *newNode = nullptr; // Pointer to a new node + + // Allocate a new node and store num there. + newNode = new StackNode; + newNode->value = num; + + // If there are no nodes in the list + // make newNode the first node. + if (isEmpty()) + { + top = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert NewNode before top. + { + newNode->next = top; + top = newNode; + } +} + +//**************************************************** +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//**************************************************** + +void DynIntStack::pop(int &num) +{ + StackNode *temp = nullptr; // Temporary pointer + + // First make sure the stack isn't empty. + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else // pop value off top of stack + { + num = top->value; + temp = top->next; + delete top; + top = temp; + } +} + +//**************************************************** +// Member function isEmpty returns true if the stack * +// is empty, or false otherwise. * +//**************************************************** + +bool DynIntStack::isEmpty() +{ + bool status; + + if (!top) + status = true; + else + status = false; + + return status; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynIntStack.h b/SourceCode/Chapter 18/DynIntStack.h new file mode 100755 index 0000000..fafa86b --- /dev/null +++ b/SourceCode/Chapter 18/DynIntStack.h @@ -0,0 +1,30 @@ +// Specification file for the DynIntStack class +#ifndef DYNINTSTACK_H +#define DYNINTSTACK_H + +class DynIntStack +{ +private: + // Structure for stack nodes + struct StackNode + { + int value; // Value in the node + StackNode *next; // Pointer to the next node + }; + + StackNode *top; // Pointer to the stack top + +public: + // Constructor + DynIntStack() + { top = nullptr; } + + // Destructor + ~DynIntStack(); + + // Stack operations + void push(int); + void pop(int &); + bool isEmpty(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynamicQueue.h b/SourceCode/Chapter 18/DynamicQueue.h new file mode 100755 index 0000000..f3bb9ad --- /dev/null +++ b/SourceCode/Chapter 18/DynamicQueue.h @@ -0,0 +1,142 @@ +#ifndef DYNAMICQUEUE_H +#define DYNAMICQUEUE_H +#include +using namespace std; + +// DynamicQueue template +template +class DynamicQueue +{ +private: + // Structure for the queue nodes + struct QueueNode + { + T value; // Value in a node + QueueNode *next; // Pointer to the next node + }; + + QueueNode *front; // The front of the queue + QueueNode *rear; // The rear of the queue + int numItems; // Number of items in the queue +public: + // Constructor + DynamicQueue(); + + // Destructor + ~DynamicQueue(); + + // Queue operations + void enqueue(T); + void dequeue(T &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; + +//******************************************** +// The constructor creates an empty queue. * +//******************************************** +template +DynamicQueue::DynamicQueue() +{ + front = nullptr; + rear = nullptr; + numItems = 0; +} + +//******************************************** +// Destructor * +//******************************************** +template +DynamicQueue::~DynamicQueue() +{ + clear(); +} + +//******************************************** +// Function enqueue inserts the value in num * +// at the rear of the queue. * +//******************************************** +template +void DynamicQueue::enqueue(T item) +{ + QueueNode *newNode = nullptr; + + // Create a new node and store num there. + newNode = new QueueNode; + newNode->value = item; + newNode->next = nullptr; + + // Adjust front and rear as necessary. + if (isEmpty()) + { + front = newNode; + rear = newNode; + } + else + { + rear->next = newNode; + rear = newNode; + } + + // Update numItems. + numItems++; +} + +//********************************************** +// Function dequeue removes the value at the * +// front of the queue, and copies it into num. * +//********************************************** +template +void DynamicQueue::dequeue(T &item) +{ + QueueNode *temp = nullptr; + + if (isEmpty()) + { + cout << "The queue is empty.\n"; + } + else + { + // Save the front node value in num. + item = front->value; + + // Remove the front node and delete it. + temp = front; + front = front->next; + delete temp; + + // Update numItems. + numItems--; + } +} + +//********************************************* +// Function isEmpty returns true if the queue * +// is empty, and false otherwise. * +//********************************************* +template +bool DynamicQueue::isEmpty() const +{ + bool status; + + if (numItems > 0) + status = false; + else + status = true; + return status; +} + +//******************************************** +// Function clear dequeues all the elements * +// in the queue. * +//******************************************** +template +void DynamicQueue::clear() +{ + T value; // Dummy variable for dequeue + + while(!isEmpty()) + dequeue(value); +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/DynamicStack.h b/SourceCode/Chapter 18/DynamicStack.h new file mode 100755 index 0000000..65c6b54 --- /dev/null +++ b/SourceCode/Chapter 18/DynamicStack.h @@ -0,0 +1,124 @@ +#ifndef DYNAMICSTACK_H +#define DYNAMICSTACK_H +#include +using namespace std; + +// Stack template +template +class DynamicStack +{ +private: + // Structure for the stach nodes + struct StackNode + { + T value; // Value in the node + StackNode *next; // Pointer to next node + }; + + StackNode *top; // Pointer to the stack top + +public: + //Constructor + DynamicStack() + { top = nullptr; } + + // Destructor + ~DynamicStack(); + + // Stack operations + void push(T); + void pop(T &); + bool isEmpty(); +}; + +//*************************************************** +// Destructor * +//*************************************************** +template +DynamicStack::~DynamicStack() +{ + StackNode *nodePtr, *nextNode; + + // Position nodePtr at the top of the stack. + nodePtr = top; + + // Traverse the list deleting each node. + while (nodePtr != nullptr) + { + nextNode = nodePtr->next; + delete nodePtr; + nodePtr = nextNode; + } +} + +//************************************************************* +// Member function push pushes the argument onto * +// the stack. * +//************************************************************* + +template +void DynamicStack::push(T item) +{ + StackNode *newNode = nullptr; // Pointer to a new node + + // Allocate a new node and store num there. + newNode = new StackNode; + newNode->value = item; + + // If there are no nodes in the list + // make newNode the first node. + if (isEmpty()) + { + top = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert NewNode before top. + { + newNode->next = top; + top = newNode; + } +} + +//************************************************************* +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//************************************************************* + +template +void DynamicStack::pop(T &item) +{ + StackNode *temp = nullptr; // Temporary pointer + + // First make sure the stack isn't empty. + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else // pop value off top of stack + { + item = top->value; + temp = top->next; + delete top; + top = temp; + } +} + +//************************************************************* +// Member function isEmpty returns true if the stack * +// is empty, or false otherwise. * +//************************************************************* + +template +bool DynamicStack::isEmpty() +{ + bool status; + + if (!top) + status = true; + else + status = false; + + return status; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntQueue.cpp b/SourceCode/Chapter 18/IntQueue.cpp new file mode 100755 index 0000000..3bbc6f7 --- /dev/null +++ b/SourceCode/Chapter 18/IntQueue.cpp @@ -0,0 +1,128 @@ +// Implementation file for the IntQueue class +#include +#include "IntQueue.h" +using namespace std; + +//*************************************************************** +// This constructor creates an empty queue of a specified size. * +//*************************************************************** + +IntQueue::IntQueue(int s) +{ + queueArray = new int[s]; + queueSize = s; + front = -1; + rear = -1; + numItems = 0; +} + +//*************************************************************** +// Copy constructor * +//*************************************************************** + +IntQueue::IntQueue(const IntQueue &obj) +{ + // Allocate the queue array. + queueArray = new int[obj.queueSize]; + + // Copy the other object's attributes. + queueSize = obj.queueSize; + front = obj.front; + rear = obj.rear; + numItems = obj.numItems; + + // Copy the other object's queue array. + for (int count = 0; count < obj.queueSize; count++) + queueArray[count] = obj.queueArray[count]; +} + +//*************************************************************** +// Destructor * +//*************************************************************** + +IntQueue::~IntQueue() +{ + delete [] queueArray; +} + +//*************************************************************** +// Function enqueue inserts a value at the rear of the queue. * +//*************************************************************** + +void IntQueue::enqueue(int num) +{ + if (isFull()) + cout << "The queue is full.\n"; + else + { + // Calculate the new rear position + rear = (rear + 1) % queueSize; + // Insert new item + queueArray[rear] = num; + // Update item count + numItems++; + } +} + +//*************************************************************** +// Function dequeue removes the value at the front of the queue * +// and copies t into num. * +//*************************************************************** + +void IntQueue::dequeue(int &num) +{ + if (isEmpty()) + cout << "The queue is empty.\n"; + else + { + // Move front + front = (front + 1) % queueSize; + // Retrieve the front item + num = queueArray[front]; + // Update item count + numItems--; + } +} + +//*************************************************************** +// isEmpty returns true if the queue is empty, otherwise false. * +//*************************************************************** + +bool IntQueue::isEmpty() const +{ + bool status; + + if (numItems) + status = false; + else + status = true; + + return status; +} + +//*************************************************************** +// isFull returns true if the queue is full, otherwise false. * +//*************************************************************** + +bool IntQueue::isFull() const +{ + bool status; + + if (numItems < queueSize) + status = false; + else + status = true; + + return status; +} + +//***************************************************************** +// clear sets the front and rear indices, and sets numItems to 0. * +//***************************************************************** + +void IntQueue::clear() +{ + front = queueSize - 1; + rear = queueSize - 1; + numItems = 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntQueue.h b/SourceCode/Chapter 18/IntQueue.h new file mode 100755 index 0000000..ec40d3b --- /dev/null +++ b/SourceCode/Chapter 18/IntQueue.h @@ -0,0 +1,30 @@ +// Specification file for the IntQueue class +#ifndef INTQUEUE_H +#define INTQUEUE_H + +class IntQueue +{ +private: + int *queueArray; // Points to the queue array + int queueSize; // The queue size + int front; // Subscript of the queue front + int rear; // Subscript of the queue rear + int numItems; // Number of items in the queue +public: + // Constructor + IntQueue(int); + + // Copy constructor + IntQueue(const IntQueue &); + + // Destructor + ~IntQueue(); + + // Queue operations + void enqueue(int); + void dequeue(int &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntStack.cpp b/SourceCode/Chapter 18/IntStack.cpp new file mode 100755 index 0000000..27c882d --- /dev/null +++ b/SourceCode/Chapter 18/IntStack.cpp @@ -0,0 +1,120 @@ +// Implementation file for the IntStach class +#include +#include "IntStack.h" +using namespace std; + +//*********************************************** +// Constructor * +// This constructor creates an empty stack. The * +// size parameter is the size of the stack. * +//*********************************************** + +IntStack::IntStack(int size) +{ + stackArray = new int[size]; + stackSize = size; + top = -1; +} + +//*********************************************** +// Copy constructor * +//*********************************************** + +IntStack::IntStack(const IntStack &obj) +{ + // Create the stack array. + if (obj.stackSize > 0) + stackArray = new int[obj.stackSize]; + else + stackArray = nullptr; + + // Copy the stackSize attribute. + stackSize = obj.stackSize; + + // Copy the stack contents. + for (int count = 0; count < stackSize; count++) + stackArray[count] = obj.stackArray[count]; + + // Set the top of the stack. + top = obj.top; +} + +//*********************************************** +// Destructor * +//*********************************************** + +IntStack::~IntStack() +{ + delete [] stackArray; +} + +//************************************************* +// Member function push pushes the argument onto * +// the stack. * +//************************************************* + +void IntStack::push(int num) +{ + if (isFull()) + { + cout << "The stack is full.\n"; + } + else + { + top++; + stackArray[top] = num; + } +} + +//**************************************************** +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//**************************************************** + +void IntStack::pop(int &num) +{ + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else + { + num = stackArray[top]; + top--; + } +} + +//*************************************************** +// Member function isFull returns true if the stack * +// is full, or false otherwise. * +//*************************************************** + +bool IntStack::isFull() const +{ + bool status; + + if (top == stackSize - 1) + status = true; + else + status = false; + + return status; +} + +//**************************************************** +// Member funciton isEmpty returns true if the stack * +// is empty, or false otherwise. * +//**************************************************** + +bool IntStack::isEmpty() const +{ + bool status; + + if (top == -1) + status = true; + else + status = false; + + return status; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/IntStack.h b/SourceCode/Chapter 18/IntStack.h new file mode 100755 index 0000000..67245a3 --- /dev/null +++ b/SourceCode/Chapter 18/IntStack.h @@ -0,0 +1,28 @@ +// Specification file for the IntStack class +#ifndef INTSTACK_H +#define INTSTACK_H + +class IntStack +{ +private: + int *stackArray; // Pointer to the stack array + int stackSize; // The stack size + int top; // Indicates the top of the stack + +public: + // Constructor + IntStack(int); + + // Copy constructor + IntStack(const IntStack &); + + // Destructor + ~IntStack(); + + // Stack operations + void push(int); + void pop(int &); + bool isFull() const; + bool isEmpty() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/MathStack.cpp b/SourceCode/Chapter 18/MathStack.cpp new file mode 100755 index 0000000..17adb6d --- /dev/null +++ b/SourceCode/Chapter 18/MathStack.cpp @@ -0,0 +1,46 @@ +// Implementation file for the MathStack class +#include "MathStack.h" + +//*********************************************** +// Member function add. add pops * +// the first two values off the stack and * +// adds them. The sum is pushed onto the stack. * +//*********************************************** + +void MathStack::add() +{ + int num, sum; + + // Pop the first two values off the stack. + pop(sum); + pop(num); + + // Add the two values, store in sum. + sum += num; + + // Push sum back onto the stack. + push(sum); +} + +//*********************************************** +// Member function sub. sub pops the * +// first two values off the stack. The * +// second value is subtracted from the * +// first value. The difference is pushed * +// onto the stack. * +//*********************************************** + +void MathStack::sub() +{ + int num, diff; + + // Pop the first two values off the stack. + pop(diff); + pop(num); + + // Subtract num from diff. + diff -= num; + + // Push diff back onto the stack. + push(diff); +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/MathStack.h b/SourceCode/Chapter 18/MathStack.h new file mode 100755 index 0000000..dc57ce4 --- /dev/null +++ b/SourceCode/Chapter 18/MathStack.h @@ -0,0 +1,16 @@ +// Specification file for the MathStack class +#ifndef MATHSTACK_H +#define MATHSTACK_H +#include "IntStack.h" + +class MathStack : public IntStack +{ +public: + // Constructor + MathStack(int s) : IntStack(s) {} + + // MathStack operations + void add(); + void sub(); +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-1.cpp b/SourceCode/Chapter 18/Pr18-1.cpp new file mode 100755 index 0000000..7254008 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-1.cpp @@ -0,0 +1,38 @@ +// This program demonstrates the IntStack class. +#include +#include "IntStack.h" +using namespace std; + +int main() +{ + int catchVar; // To hold values popped off the stack + + // Define a stack object to hold 5 values. + IntStack stack(5); + + // Push the values 5, 10, 15, 20, and 25 onto the stack. + cout << "Pushing 5\n"; + stack.push(5); + cout << "Pushing 10\n"; + stack.push(10); + cout << "Pushing 15\n"; + stack.push(15); + cout << "Pushing 20\n"; + stack.push(20); + cout << "Pushing 25\n"; + stack.push(25); + + // Pop the values off the stack. + cout << "Popping...\n"; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-10.cpp b/SourceCode/Chapter 18/Pr18-10.cpp new file mode 100755 index 0000000..165c42c --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-10.cpp @@ -0,0 +1,32 @@ +// This program demonstrates the DynamicQueue template. +#include +#include +#include "DynamicQueue.h" +using namespace std; + +const int QUEUE_SIZE = 5; + +int main() +{ + string name; + + // Create a Queue. + DynamicQueue queue; + + // Enqueue some names. + for (int count = 0; count < QUEUE_SIZE; count++) + { + cout << "Enter an name: "; + getline(cin, name); + queue.enqueue(name); + } + + // Dequeue the names and display them. + cout << "\nHere are the names you entered:\n"; + for (int count = 0; count < QUEUE_SIZE; count++) + { + queue.dequeue(name); + cout << name << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-11.cpp b/SourceCode/Chapter 18/Pr18-11.cpp new file mode 100755 index 0000000..d87e044 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-11.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the STL deque container. +#include +#include +using namespace std; + +int main() +{ + const int MAX = 8; // Max value + int count; // Loop counter + + // Create a deque object. + deque iDeque; + + // Enqueue a series of numbers. + cout << "I will now enqueue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Pushing " << count << endl; + iDeque.push_back(count); + } + + // Dequeue and display the numbers. + cout << "I will now dequeue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Popping "<< iDeque.front() << endl; + iDeque.pop_front(); + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-12.cpp b/SourceCode/Chapter 18/Pr18-12.cpp new file mode 100755 index 0000000..2e753c2 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-12.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the STL queue container adapter. +#include +#include +using namespace std; + +int main() +{ + const int MAX = 8; // Max value + int count; // Loop counter + + // Define a queue object. + queue iQueue; + + // Enqueue a series of numbers. + cout << "I will now enqueue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Pushing " << count << endl; + iQueue.push(count); + } + + // Dequeue and display the numbers. + cout << "I will now dequeue items...\n"; + for (count = 2; count < MAX; count += 2) + { + cout << "Popping " << iQueue.front() << endl; + iQueue.pop(); + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-2.cpp b/SourceCode/Chapter 18/Pr18-2.cpp new file mode 100755 index 0000000..48b9a0f --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-2.cpp @@ -0,0 +1,41 @@ +// This program demonstrates the MathStack class. +#include +#include "MathStack.h" +using namespace std; + +int main() +{ + int catchVar; // To hold values popped off the stack + + // Create a MathStack object. + MathStack stack(5); + + // Push 3 and 6 onto the stack. + cout << "Pushing 3\n"; + stack.push(3); + cout << "Pushing 6\n"; + stack.push(6); + + // Add the two values. + stack.add(); + + // Pop the sum off the stack and display it. + cout << "The sum is "; + stack.pop(catchVar); + cout << catchVar << endl << endl; + + // Push 7 and 10 onto the stack + cout << "Pushing 7\n"; + stack.push(7); + cout << "Pushing 10\n"; + stack.push(10); + + // Subtract 7 from 10. + stack.sub(); + + // Pop the difference off the stack and display it. + cout << "The difference is "; + stack.pop(catchVar); + cout << catchVar << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-3.cpp b/SourceCode/Chapter 18/Pr18-3.cpp new file mode 100755 index 0000000..eacc704 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-3.cpp @@ -0,0 +1,124 @@ +// This program demonstrates the Stack template. +#include +#include +#include "Stack.h" +using namespace std; + +// Constants for the menu choices +const int PUSH_CHOICE = 1, + POP_CHOICE = 2, + QUIT_CHOICE = 3; + +// Function prototypes +void menu(int &); +void getStackSize(int &); +void pushItem(Stack&); +void popItem(Stack&); + +int main() +{ + int stackSize; // The stack size + int choice; // To hold a menu choice + + // Get the stack size. + getStackSize(stackSize); + + // Create the stack. + Stack stack(stackSize); + + do + { + // Get the user's menu choice. + menu(choice); + + // Perform the user's choice. + if (choice != QUIT_CHOICE) + { + switch (choice) + { + case PUSH_CHOICE: + pushItem(stack); + break; + case POP_CHOICE: + popItem(stack); + } + } + } while (choice != QUIT_CHOICE); + + return 0; +} + +//************************************************ +// The getStackSize function gets the desired * +// stack size, which is assigned to the * +// reference parameter. * +//************************************************ +void getStackSize(int &size) +{ + // Get the desired stack size. + cout << "How big should I make the stack? "; + cin >> size; + + // Validate the size. + while (size < 1) + { + cout << "Enter 1 or greater: "; + cin >> size; + } +} + +//************************************************ +// The menu function displays the menu and gets * +// the user's choice, which is assigned to the * +// reference parameter. * +//************************************************ +void menu(int &choice) +{ + // Display the menu and get the user's choice. + cout << "\nWhat do you want to do?\n" + << PUSH_CHOICE + << " - Push an item onto the stack\n" + << POP_CHOICE + << " - Pop an item off the stack\n" + << QUIT_CHOICE + << " - Quit the program\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the choice + while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) + { + cout << "Enter a valid choice: "; + cin >> choice; + } +} + +//************************************************ +// The pushItem function gets an item from the * +// user and pushes it onto the stack. * +//************************************************ +void pushItem(Stack &stack) +{ + string item; + + // Get an item to push onto the stack. + cin.ignore(); + cout << "\nEnter an item: "; + getline(cin, item); + stack.push(item); +} + +//*************************************************** +// The popItem function pops an item from the stack * +//*************************************************** +void popItem(Stack &stack) +{ + string item = ""; + + // Pop the item. + stack.pop(item); + + // Display the item. + if (item != "") + cout << item << " was popped.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-4.cpp b/SourceCode/Chapter 18/Pr18-4.cpp new file mode 100755 index 0000000..ed63e73 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-4.cpp @@ -0,0 +1,35 @@ +// This program demonstrates the dynamic stack +// class DynIntClass. +#include +#include "DynIntStack.h" +using namespace std; + +int main() +{ + int catchVar; // To hold values popped off the stack + + // Create a DynIntStack object. + DynIntStack stack; + + // Push 5, 10, and 15 onto the stack. + cout << "Pushing 5\n"; + stack.push(5); + cout << "Pushing 10\n"; + stack.push(10); + cout << "Pushing 15\n"; + stack.push(15); + + // Pop the values off the stack and display them. + cout << "Popping...\n"; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + stack.pop(catchVar); + cout << catchVar << endl; + + // Try to pop another value off the stack. + cout << "\nAttempting to pop again... "; + stack.pop(catchVar); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-5.cpp b/SourceCode/Chapter 18/Pr18-5.cpp new file mode 100755 index 0000000..4fcf121 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-5.cpp @@ -0,0 +1,100 @@ +#include +#include +#include "DynamicStack.h" +using namespace std; + +// Constants for the menu choices +const int PUSH_CHOICE = 1, + POP_CHOICE = 2, + QUIT_CHOICE = 3; + +// Function prototypes +void menu(int &); +void getStackSize(int &); +void pushItem(DynamicStack &); +void popItem(DynamicStack &); + +int main() +{ + int choice; // To hold a menu choice + + // Create the stack. + DynamicStack stack; + + do + { + // Get the user's menu choice. + menu(choice); + + // Perform the user's choice. + if (choice != QUIT_CHOICE) + { + switch (choice) + { + case PUSH_CHOICE: + pushItem(stack); + break; + case POP_CHOICE: + popItem(stack); + } + } + } while (choice != QUIT_CHOICE); + + return 0; +} + +//************************************************ +// The menu function displays the menu and gets * +// the user's choice, which is assigned to the * +// reference parameter. * +//************************************************ +void menu(int &choice) +{ + // Display the menu and get the user's choice. + cout << "What do you want to do?\n" + << PUSH_CHOICE + << " - Push an item onto the stack\n" + << POP_CHOICE + << " - Pop an item off the stack\n" + << QUIT_CHOICE + << " - Quit the program\n" + << "Enter your choice: "; + cin >> choice; + + // Validate the choice + while (choice < PUSH_CHOICE || choice > QUIT_CHOICE) + { + cout << "Enter a valid choice: "; + cin >> choice; + } +} + +//************************************************ +// The pushItem function gets an item from the * +// user and pushes it onto the stack. * +//************************************************ +void pushItem(DynamicStack &stack) +{ + string item; + + // Get an item to push onto the stack. + cin.ignore(); + cout << "\nEnter an item: "; + getline(cin, item); + stack.push(item); +} + +//*************************************************** +// The popItem function pops an item from the stack * +//*************************************************** +void popItem(DynamicStack &stack) +{ + string item = ""; + + // Pop the item. + stack.pop(item); + + // Display the item. + if (item != "") + cout << item << " was popped.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-6.cpp b/SourceCode/Chapter 18/Pr18-6.cpp new file mode 100755 index 0000000..265419b --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-6.cpp @@ -0,0 +1,34 @@ +// This program demonstrates the STL stack +// container adapter. +#include +#include +#include +using namespace std; + +int main() +{ + const int MAX = 8; // Max value to store in the stack + int count; // Loop counter + + // Define an STL stack + stack< int, vector > iStack; + + // Push values onto the stack. + for (count = 2; count < MAX; count += 2) + { + cout << "Pushing " << count << endl; + iStack.push(count); + } + + // Display the size of the stack. + cout << "The size of the stack is "; + cout << iStack.size() << endl; + + // Pop the values of the stack. + for (count = 2; count < MAX; count += 2) + { + cout << "Popping " << iStack.top() << endl; + iStack.pop(); + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-7.cpp b/SourceCode/Chapter 18/Pr18-7.cpp new file mode 100755 index 0000000..0e74a8b --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-7.cpp @@ -0,0 +1,31 @@ +// This program demonstrates the IntQueue class. +#include +#include "IntQueue.h" +using namespace std; + +int main() +{ + const int MAX_VALUES = 5; // Max number of values + + // Create an IntQueue to hold the values. + IntQueue iQueue(MAX_VALUES); + + // Enqueue a series of items. + cout << "Enqueuing " << MAX_VALUES << " items...\n"; + for (int x = 0; x < MAX_VALUES; x++) + iQueue.enqueue(x); + + // Attempt to enqueue just one more item. + cout << "Now attempting to enqueue again...\n"; + iQueue.enqueue(MAX_VALUES); + + // Dequeue and retrieve all items in the queue. + cout << "The values in the queue were:\n"; + while (!iQueue.isEmpty()) + { + int value; + iQueue.dequeue(value); + cout << value << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-8.cpp b/SourceCode/Chapter 18/Pr18-8.cpp new file mode 100755 index 0000000..dec173e --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-8.cpp @@ -0,0 +1,32 @@ +// This program demonstrates the Queue template. +#include +#include +#include "Queue.h" +using namespace std; + +const int QUEUE_SIZE = 5; + +int main() +{ + string name; + + // Create a Queue. + Queue queue(QUEUE_SIZE); + + // Enqueue some names. + for (int count = 0; count < QUEUE_SIZE; count++) + { + cout << "Enter an name: "; + getline(cin, name); + queue.enqueue(name); + } + + // Dequeue the names and display them. + cout << "\nHere are the names you entered:\n"; + for (int count = 0; count < QUEUE_SIZE; count++) + { + queue.dequeue(name); + cout << name << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Pr18-9.cpp b/SourceCode/Chapter 18/Pr18-9.cpp new file mode 100755 index 0000000..8b053a6 --- /dev/null +++ b/SourceCode/Chapter 18/Pr18-9.cpp @@ -0,0 +1,27 @@ +// This program demonstrates the DynIntQueue class. +#include +#include "DynIntQueue.h" +using namespace std; + +int main() +{ + const int MAX_VALUES = 5; + + // Create a DynIntQueue object. + DynIntQueue iQueue; + + // Enqueue a series of numbers. + cout << "Enqueuing " << MAX_VALUES << " items...\n"; + for (int x = 0; x < 5; x++) + iQueue.enqueue(x); + + // Dequeue and retrieve all numbers in the queue + cout << "The values in the queue were:\n"; + while (!iQueue.isEmpty()) + { + int value; + iQueue.dequeue(value); + cout << value << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 18/Queue.h b/SourceCode/Chapter 18/Queue.h new file mode 100755 index 0000000..7b2d91c --- /dev/null +++ b/SourceCode/Chapter 18/Queue.h @@ -0,0 +1,157 @@ +#ifndef QUEUE_H +#define QUEUE_H +#include +using namespace std; + +// Stack template +template +class Queue +{ +private: + T *queueArray; // Points to the queue array + int queueSize; // The queue size + int front; // Subscript of the queue front + int rear; // Subscript of the queue rear + int numItems; // Number of items in the queue +public: + // Constructor + Queue(int); + + // Copy constructor + Queue(const Queue &); + + // Destructor + ~Queue(); + + // Queue operations + void enqueue(T); + void dequeue(T &); + bool isEmpty() const; + bool isFull() const; + void clear(); +}; + +//*************************************************************** +// This constructor creates an empty queue of a specified size. * +//*************************************************************** +template +Queue::Queue(int s) +{ + queueArray = new T[s]; + queueSize = s; + front = -1; + rear = -1; + numItems = 0; +} + +//*************************************************************** +// Copy constructor * +//*************************************************************** +template +Queue::Queue(const Queue &obj) +{ + // Allocate the queue array. + queueArray = new T[obj.queueSize]; + + // Copy the other object's attributes. + queueSize = obj.queueSize; + front = obj.front; + rear = obj.rear; + numItems = obj.numItems; + + // Copy the other object's queue array. + for (int count = 0; count < obj.queueSize; count++) + queueArray[count] = obj.queueArray[count]; +} + +//*************************************************************** +// Destructor * +//*************************************************************** +template +Queue::~Queue() +{ + delete [] queueArray; +} + +//*************************************************************** +// Function enqueue inserts a value at the rear of the queue. * +//*************************************************************** +template +void Queue::enqueue(T item) +{ + if (isFull()) + cout << "The queue is full.\n"; + else + { + // Calculate the new rear position + rear = (rear + 1) % queueSize; + // Insert new item + queueArray[rear] = item; + // Update item count + numItems++; + } +} + +//*************************************************************** +// Function dequeue removes the value at the front of the queue * +// and copies t into num. * +//*************************************************************** +template +void Queue::dequeue(T &item) +{ + if (isEmpty()) + cout << "The queue is empty.\n"; + else + { + // Move front + front = (front + 1) % queueSize; + // Retrieve the front item + item = queueArray[front]; + // Update item count + numItems--; + } +} + +//*************************************************************** +// isEmpty returns true if the queue is empty, otherwise false. * +//*************************************************************** +template +bool Queue::isEmpty() const +{ + bool status; + + if (numItems) + status = false; + else + status = true; + + return status; +} + +//*************************************************************** +// isFull returns true if the queue is full, otherwise false. * +//*************************************************************** +template +bool Queue::isFull() const +{ + bool status; + + if (numItems < queueSize) + status = false; + else + status = true; + + return status; +} + +//***************************************************************** +// clear sets the front and rear indices, and sets numItems to 0. * +//***************************************************************** +template +void Queue::clear() +{ + front = queueSize - 1; + rear = queueSize - 1; + numItems = 0; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 18/Stack.h b/SourceCode/Chapter 18/Stack.h new file mode 100755 index 0000000..5c18d0e --- /dev/null +++ b/SourceCode/Chapter 18/Stack.h @@ -0,0 +1,153 @@ +#ifndef STACK_H +#define STACK_H +#include +using namespace std; + +// Stack template +template +class Stack +{ +private: + T *stackArray; + int stackSize; + int top; + +public: + //Constructor + Stack(int); + + // Copy constructor + Stack(const Stack&); + + // Destructor + ~Stack(); + + // Stack operations + void push(T); + void pop(T &); + bool isFull(); + bool isEmpty(); +}; + +//*************************************************** +// Constructor * +//*************************************************** + +template +Stack::Stack(int size) +{ + stackArray = new T[size]; + stackSize = size; + top = -1; +} + +//*************************************************** +// Copy constructor * +//*************************************************** + +template +Stack::Stack(const Stack &obj) +{ + // Create the stack array. + if (obj.stackSize > 0) + stackArray = new T[obj.stackSize]; + else + stackArray = nullptr; + + // Copy the stackSize attribute. + stackSize = obj.stackSize; + + // Copy the stack contents. + for (int count = 0; count < stackSize; count++) + stackArray[count] = obj.stackArray[count]; + + // Set the top of the stack. + top = obj.top; +} + +//*************************************************** +// Destructor * +//*************************************************** + +template +Stack::~Stack() +{ + if (stackSize > 0) + delete [] stackArray; +} + +//************************************************************* +// Member function push pushes the argument onto * +// the stack. * +//************************************************************* + +template +void Stack::push(T item) +{ + if (isFull()) + { + cout << "The stack is full.\n"; + } + else + { + top++; + stackArray[top] = item; + } +} + +//************************************************************* +// Member function pop pops the value at the top * +// of the stack off, and copies it into the variable * +// passed as an argument. * +//************************************************************* + +template +void Stack::pop(T &item) +{ + if (isEmpty()) + { + cout << "The stack is empty.\n"; + } + else + { + item = stackArray[top]; + top--; + } +} + +//************************************************************* +// Member function isFull returns true if the stack * +// is full, or false otherwise. * +//************************************************************* + +template +bool Stack::isFull() +{ + bool status; + + if (top == stackSize - 1) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Member function isEmpty returns true if the stack * +// is empty, or false otherwise. * +//************************************************************* + +template +bool Stack::isEmpty() +{ + bool status; + + if (top == -1) + status = true; + else + status = false; + + return status; +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 19/NumberList.cpp b/SourceCode/Chapter 19/NumberList.cpp new file mode 100755 index 0000000..ccde20f --- /dev/null +++ b/SourceCode/Chapter 19/NumberList.cpp @@ -0,0 +1,215 @@ +// Implementation file for the NumberList class +#include // For cout +#include "NumberList.h" +using namespace std; + +//************************************************** +// appendNode appends a node containing the * +// value pased into num, to the end of the list. * +//************************************************** + +void NumberList::appendNode(double num) +{ + ListNode *newNode; // To point to a new node + ListNode *nodePtr; // To move through the list + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + newNode->next = nullptr; + + // If there are no nodes in the list + // make newNode the first node. + if (!head) + head = newNode; + else // Otherwise, insert newNode at end. + { + // Initialize nodePtr to head of list. + nodePtr = head; + + // Find the last node in the list. + while (nodePtr->next) + nodePtr = nodePtr->next; + + // Insert newNode as the last node. + nodePtr->next = newNode; + } +} + +//************************************************** +// displayList shows the value * +// stored in each node of the linked list * +// pointed to by head. * +//************************************************** + +void NumberList::displayList() const +{ + ListNode *nodePtr; // To move through the list + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr points to a node, traverse + // the list. + while (nodePtr) + { + // Display the value in this node. + cout << nodePtr->value << endl; + + // Move to the next node. + nodePtr = nodePtr->next; + } +} + +//************************************************** +// The insertNode function inserts a node with * +// num copied to its value member. * +//************************************************** + +void NumberList::insertNode(double num) +{ + ListNode *newNode; // A new node + ListNode *nodePtr; // To traverse the list + ListNode *previousNode = nullptr; // The previous node + + // Allocate a new node and store num there. + newNode = new ListNode; + newNode->value = num; + + // If there are no nodes in the list + // make newNode the first node + if (!head) + { + head = newNode; + newNode->next = nullptr; + } + else // Otherwise, insert newNode + { + // Position nodePtr at the head of list. + nodePtr = head; + + // Initialize previousNode to nullptr. + previousNode = nullptr; + + // Skip all nodes whose value is less than num. + while (nodePtr != nullptr && nodePtr->value < num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If the new node is to be the 1st in the list, + // insert it before all other nodes. + if (previousNode == nullptr) + { + head = newNode; + newNode->next = nodePtr; + } + else // Otherwise insert after the previous node. + { + previousNode->next = newNode; + newNode->next = nodePtr; + } + } +} + +//************************************************** +// The deleteNode function searches for a node * +// with num as its value. The node, if found, is * +// deleted from the list and from memory. * +//************************************************** + +void NumberList::deleteNode(double num) +{ + ListNode *nodePtr; // To traverse the list + ListNode *previousNode; // To point to the previous node + + // If the list is empty, do nothing. + if (!head) + return; + + // Determine if the first node is the one. + if (head->value == num) + { + nodePtr = head->next; + delete head; + head = nodePtr; + } + else + { + // Initialize nodePtr to head of list + nodePtr = head; + + // Skip all nodes whose value member is + // not equal to num. + while (nodePtr != nullptr && nodePtr->value != num) + { + previousNode = nodePtr; + nodePtr = nodePtr->next; + } + + // If nodePtr is not at the end of the list, + // link the previous node to the node after + // nodePtr, then delete nodePtr. + if (nodePtr) + { + previousNode->next = nodePtr->next; + delete nodePtr; + } + } +} + +//************************************************** +// Destructor * +// This function deletes every node in the list. * +//************************************************** + +NumberList::~NumberList() +{ + ListNode *nodePtr; // To traverse the list + ListNode *nextNode; // To point to the next node + + // Position nodePtr at the head of the list. + nodePtr = head; + + // While nodePtr is not at the end of the list... + while (nodePtr != nullptr) + { + // Save a pointer to the next node. + nextNode = nodePtr->next; + + // Delete the current node. + delete nodePtr; + + // Position nodePtr at the next node. + nodePtr = nextNode; + } +} + +//************************************************** +// countNodes is a recursive function that returns * +// the number of nodes in the list. * +//************************************************** + +int NumberList::countNodes(ListNode *nodePtr) const +{ + if (nodePtr != nullptr) + return 1 + countNodes(nodePtr->next); + else + return 0; +} + +//**************************************************** +// showReverse is a recursive function that displays * +// the values stored in the list in reverse. The * +// function is called from DisplayBackwards. * +//**************************************************** + +void NumberList::showReverse(ListNode *nodePtr) const +{ + if (nodePtr != nullptr) + { + showReverse(nodePtr->next); + cout << nodePtr->value << " "; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/NumberList.h b/SourceCode/Chapter 19/NumberList.h new file mode 100755 index 0000000..11bc3cb --- /dev/null +++ b/SourceCode/Chapter 19/NumberList.h @@ -0,0 +1,39 @@ +// Specification file for the NumberList class +#ifndef NUMBERLIST_H +#define NUMBERLIST_H + +class NumberList +{ +private: + // Declare a structure for the list + struct ListNode + { + double value; + struct ListNode *next; + }; + + ListNode *head; // List head pointer + + // Private member functions + int countNodes(ListNode *) const; + void showReverse(ListNode *) const; + +public: + // Constructor + NumberList() + { head = nullptr; } + + // Destructor + ~NumberList(); + + // Linked List Operations + void appendNode(double); + void insertNode(double); + void deleteNode(double); + void displayList() const; + int numNodes() const + { return countNodes(head); } + void displayBackwards() const + { showReverse(head); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-1.cpp b/SourceCode/Chapter 19/Pr19-1.cpp new file mode 100755 index 0000000..be97492 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-1.cpp @@ -0,0 +1,28 @@ +// This program demonstrates a simple recursive function. +#include +using namespace std; + +// Function prototype +void message(int); + +int main() +{ + message(5); + return 0; +} + +//*********************************************************** +// Definition of function Message. If the value in times is * +// greater than 0, the message is displayed and the * +// function is recursively called with the argument * +// times - 1. * +//*********************************************************** + +void message(int times) +{ + if (times > 0) + { + cout << "This is a recursive function.\n"; + message(times - 1); + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-10.cpp b/SourceCode/Chapter 19/Pr19-10.cpp new file mode 100755 index 0000000..fb5762e --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-10.cpp @@ -0,0 +1,41 @@ +// This program displays a solution to the Towers of +// Hanoi game. +#include +using namespace std; + +// Function prototype +void moveDiscs(int, int, int, int); + +int main() +{ + const int NUM_DISCS = 3; // Number of discs to move + const int FROM_PEG = 1; // Initial "from" peg + const int TO_PEG = 3; // Initial "to" peg + const int TEMP_PEG = 2; // Initial "temp" peg + + // Play the game. + moveDiscs(NUM_DISCS, FROM_PEG, TO_PEG, TEMP_PEG); + cout << "All the pegs are moved!\n"; + return 0; +} + +//*************************************************** +// The moveDiscs function displays a disc move in * +// the Towers of Hanoi game. * +// The parameters are: * +// num: The number of discs to move. * +// fromPeg: The peg to move from. * +// toPeg: The peg to move to. * +// tempPeg: The temporary peg. * +//*************************************************** + +void moveDiscs(int num, int fromPeg, int toPeg, int tempPeg) +{ + if (num > 0) + { + moveDiscs(num - 1, fromPeg, tempPeg, toPeg); + cout << "Move a disc from peg " << fromPeg + << " to peg " << toPeg << endl; + moveDiscs(num - 1, tempPeg, toPeg, fromPeg); + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-11.cpp b/SourceCode/Chapter 19/Pr19-11.cpp new file mode 100755 index 0000000..1f05ec2 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-11.cpp @@ -0,0 +1,89 @@ +// This program demonstrates the QuickSort Algorithm. +#include +using namespace std; + +// Function prototypes +void quickSort(int [], int, int); +int partition(int [], int, int); +void swap(int &, int &); + +int main() +{ + const int SIZE = 10; // Array size + int count; // Loop counter + int array[SIZE] = {7, 3, 9, 2, 0, 1, 8, 4, 6, 5}; + + // Display the array contents. + for (count = 0; count < SIZE; count++) + cout << array[count] << " "; + cout << endl; + + // Sort the array. + quickSort(array, 0, SIZE - 1); + + // Display the array contents. + for (count = 0; count < SIZE; count++) + cout << array[count] << " "; + cout << endl; + return 0; +} + +//************************************************ +// quickSort uses the quicksort algorithm to * +// sort set, from set[start] through set[end]. * +//************************************************ + +void quickSort(int set[], int start, int end) +{ + int pivotPoint; + + if (start < end) + { + // Get the pivot point. + pivotPoint = partition(set, start, end); + // Sort the first sub list. + quickSort(set, start, pivotPoint - 1); + // Sort the second sub list. + quickSort(set, pivotPoint + 1, end); + } +} + +//********************************************************** +// partition selects the value in the middle of the * +// array set as the pivot. The list is rearranged so * +// all the values less than the pivot are on its left * +// and all the values greater than pivot are on its right. * +//********************************************************** + +int partition(int set[], int start, int end) +{ + int pivotValue, pivotIndex, mid; + + mid = (start + end) / 2; + swap(set[start], set[mid]); + pivotIndex = start; + pivotValue = set[start]; + for (int scan = start + 1; scan <= end; scan++) + { + if (set[scan] < pivotValue) + { + pivotIndex++; + swap(set[pivotIndex], set[scan]); + } + } + swap(set[start], set[pivotIndex]); + return pivotIndex; +} + +//********************************************** +// swap simply exchanges the contents of * +// value1 and value2. * +//********************************************** + +void swap(int &value1, int &value2) +{ + int temp = value1; + + value1 = value2; + value2 = temp; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-12.cpp b/SourceCode/Chapter 19/Pr19-12.cpp new file mode 100755 index 0000000..d411b27 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-12.cpp @@ -0,0 +1,108 @@ +// This program demonstrates a recursive function that exhaustively +// searches through all possible combinations of coin values to find +// the best way to make change for a specified amount. +#include +using namespace std; + +// Constants +const int MAX_COINS_CHANGE = 100; // Max number of coins to give in change +const int MAX_COIN_VALUES = 6; // Max number of coin values +const int NO_SOLUTION = INT_MAX; // Indicates no solution + +// Function prototype +void makeChange(int, int, int[], int); + +// coinValues - global array of coin values to choose from +int coinValues[MAX_COIN_VALUES] = {100, 50, 25, 10, 5, 1 }; + +// bestCoins - global array of best coins to make change with +int bestCoins[MAX_COINS_CHANGE]; + +// Global variables +int numBestCoins = NO_SOLUTION, // Number of coins in bestCoins + numSolutions = 0, // Number of ways to make change + numCoins; // Number of allowable coins + + +int main() +{ + int coinsUsed[MAX_COINS_CHANGE], // List of coins used + numCoinsUsed = 0, // The number coins used + amount; // The amount to make change for + + // Display the possible coin values. + cout << "Here are the valid coin values, in cents: "; + for (int index = 0; index < 5; index++) + cout << coinValues[index] << " "; + cout << endl; + + // Get input from the user. + cout << "Enter the amount of cents (as an integer) " + << "to make change for: "; + cin >> amount; + cout << "What is the maximum number of coins to give as change? "; + cin >> numCoins; + + // Call the recursive function. + makeChange(numCoins, amount, coinsUsed, numCoinsUsed); + + // Display the results. + cout << "Number of possible combinations: " << numSolutions << endl; + cout << "Best combination of coins:\n"; + if (numBestCoins == NO_SOLUTION) + cout << "\tNo solution\n"; + else + { + for (int count = 0; count < numBestCoins; count++) + cout << bestCoins[count] << " "; + } + cout << endl; + return 0; +} + +//********************************************************************** +// Function makeChange. This function uses the following parameters: * +// coinsLeft - The number of coins left to choose from. * +// amount - The amount to make change for. * +// coinsUsed - An array that contains the coin values used so far. * +// numCoinsUsed - The number of values in the coinsUsed array. * +// * +// This recursive function finds all the possible ways to make change * +// for the value in amount. The best combination of coins is stored in * +// the array bestCoins. * +//********************************************************************** + +void makeChange(int coinsLeft, int amount, int coinsUsed[], + int numCoinsUsed) +{ + int coinPos, // To calculate array position of coin being used + count; // Loop counter + + if (coinsLeft == 0) // If no more coins are left + return; + else if (amount < 0) // If amount to make change for is negative + return; + else if (amount == 0) // If solution is found + { + // Store as bestCoins if best + if (numCoinsUsed < numBestCoins) + { + for (count = 0; count < numCoinsUsed; count++) + bestCoins[count] = coinsUsed[count]; + numBestCoins = numCoinsUsed; + } + numSolutions++; + return; + } + + // Find the other combinations using the coin + coinPos = numCoins - coinsLeft; + coinsUsed[numCoinsUsed] = coinValues[coinPos]; + numCoinsUsed++; + makeChange(coinsLeft, amount - coinValues[coinPos], + coinsUsed, numCoinsUsed); + + // Find the other combinations not using the coin. + numCoinsUsed--; + makeChange(coinsLeft - 1, amount, coinsUsed, numCoinsUsed); +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-2.cpp b/SourceCode/Chapter 19/Pr19-2.cpp new file mode 100755 index 0000000..c4e2199 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-2.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a simple recursive function. +#include +using namespace std; + +// Function prototype +void message(int); + +int main() +{ + message(5); + return 0; +} + +//************************************************************ +// Definition of function message. If the value in times is * +// greater than 0, the message is displayed and the function * +// is recursively called with the argument times - 1. * +//************************************************************ + +void message(int times) +{ + cout << "message called with " << times << " in times.\n"; + + if (times > 0) + { + cout << "This is a recursive function.\n"; + message(times - 1); + } + + cout << "message returning with " << times; + cout << " in times.\n"; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-3.cpp b/SourceCode/Chapter 19/Pr19-3.cpp new file mode 100755 index 0000000..413538a --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-3.cpp @@ -0,0 +1,35 @@ +// This program demonstrates a recursive function to +// calculate the factorial of a number. +#include +using namespace std; + +// Function prototype +int factorial(int); + +int main() +{ + int number; + + // Get a number from the user. + cout << "Enter an integer value and I will display\n"; + cout << "its factorial: "; + cin >> number; + + // Display the factorial of the number. + cout << "The factorial of " << number << " is "; + cout << factorial(number) << endl; + return 0; +} + +//************************************************************* +// Definition of factorial. A recursive function to calculate * +// the factorial of the parameter n. * +//************************************************************* + +int factorial(int n) +{ + if (n == 0) + return 1; // Base case + else + return n * factorial(n - 1); // Recursive case +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-4.cpp b/SourceCode/Chapter 19/Pr19-4.cpp new file mode 100755 index 0000000..62b1226 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-4.cpp @@ -0,0 +1,50 @@ +// This program demonstrates a recursive function for counting +// the number of times a character appears in a string. +#include +#include +using namespace std; + +// Function prototype +int numChars(char, string, int); + +int main() +{ + string str = "abcddddef"; + + // Display the number of times the letter + // 'd' appears in the string. + cout << "The letter d appears " + << numChars('d', str, 0) << " times.\n"; + + return 0; +} + +//************************************************ +// Function numChars. This recursive function * +// counts the number of times the character * +// search appears in the string str. The search * +// begins at the subscript stored in subscript. * +//************************************************ + +int numChars(char search, string str, int subscript) +{ + if (subscript >= str.length()) + { + // Base case: The end of the string is reached. + return 0; + } + else if (str[subscript] == search) + { + // Recursive case: A matching character was found. + // Return 1 plus the number of times the search + // search appears in the rest of the string. + return 1 + numChars(search, str, subscript+1); + } + else + { + // Recursive case: A character that does not match the + // search character was found. Return the number of times + // the search character appears in the rest of the string. + return numChars(search, str, subscript+1); + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-5.cpp b/SourceCode/Chapter 19/Pr19-5.cpp new file mode 100755 index 0000000..e3114f3 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-5.cpp @@ -0,0 +1,36 @@ +// This program demonstrates a recursive function to calculate +// the greatest common divisor (gcd) of two numbers. +#include +using namespace std; + +// Function prototype +int gcd(int, int); + +int main() +{ + int num1, num2; + + // Get two numbers. + cout << "Enter two integers: "; + cin >> num1 >> num2; + + // Display the GCD of the numbers. + cout << "The greatest common divisor of " << num1; + cout << " and " << num2 << " is "; + cout << gcd(num1, num2) << endl; + return 0; +} + +//********************************************************* +// Definition of gcd. This function uses recursion to * +// calculate the greatest common divisor of two integers, * +// passed into the parameters x and y. * +//********************************************************* + +int gcd(int x, int y) +{ + if (x % y == 0) + return y; // Base case + else + return gcd(y, x % y); // Recusrsive case +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-6.cpp b/SourceCode/Chapter 19/Pr19-6.cpp new file mode 100755 index 0000000..aeab8df --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-6.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a recursive function +// that calculates Fibonacci numbers. +#include +using namespace std; + +// Function prototype +int fib(int); + +int main() +{ + cout << "The first 10 Fibonacci numbers are:\n"; + for (int x = 0; x < 10; x++) + cout << fib(x) << " "; + cout << endl; + return 0; +} + +//***************************************** +// Function fib. Accepts an int argument * +// in n. This function returns the nth * +// Fibonacci number. * +//***************************************** + +int fib(int n) +{ + if (n <= 0) + return 0; // Base case + else if (n == 1) + return 1; // Base case + else + return fib(n - 1) + fib(n - 2); // Recursive case +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-7.cpp b/SourceCode/Chapter 19/Pr19-7.cpp new file mode 100755 index 0000000..1c527cb --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-7.cpp @@ -0,0 +1,21 @@ +// This program counts the nodes in a list. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + const int MAX = 10; // Maximum number of values + + // Define a NumberList object. + NumberList list; + + // Build the list with a series of numbers. + for (int x = 0; x < MAX; x++) + list.insertNode(x); + + // Display the number of nodes in the list. + cout << "The number of nodes is " + << list.numNodes() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-8.cpp b/SourceCode/Chapter 19/Pr19-8.cpp new file mode 100755 index 0000000..9500569 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-8.cpp @@ -0,0 +1,26 @@ +// This program demonstrates the recursive function +// for displaying the list’s nodes in reverse. +#include +#include "NumberList.h" +using namespace std; + +int main() +{ + const double MAX = 10.0; // Upper limit of values + + // Create a NumberList object. + NumberList list; + + // Add a series of numbers to the list. + for (double x = 1.5; x < MAX; x += 1.1) + list.appendNode(x); + + // Display the values in the list. + cout << "Here are the values in the list:\n"; + list.displayList(); + + // Display the values in reverse order. + cout << "Here are the values in reverse order:\n"; + list.displayBackwards(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 19/Pr19-9.cpp b/SourceCode/Chapter 19/Pr19-9.cpp new file mode 100755 index 0000000..e1f1f44 --- /dev/null +++ b/SourceCode/Chapter 19/Pr19-9.cpp @@ -0,0 +1,61 @@ +// This program demonstrates the recursive binarySearch function. +#include +using namespace std; + +// Function prototype +int binarySearch(int [], int, int, int); + +const int SIZE = 20; // Array size + +int main() +{ + // Define an array of employee ID numbers + int tests[SIZE] = {101, 142, 147, 189, 199, 207, 222, + 234, 289, 296, 310, 319, 388, 394, + 417, 429, 447, 521, 536, 600}; + int empID; // To hold an ID number + int results; // To hold the search results + + // Get an employee ID number to search for. + cout << "Enter the Employee ID you wish to search for: "; + cin >> empID; + + // Search for the ID number in the array. + results = binarySearch(tests, 0, SIZE - 1, empID); + + // Display the results of the search. + if (results == -1) + cout << "That number does not exist in the array.\n"; + else + { + cout << "That ID is found at element " << results; + cout << " in the array\n"; + } + return 0; +} + +//*************************************************************** +// The binarySearch function performs a recursive binary search * +// on a range of elements of an integer array passed into the * +// parameter array. The parameter first holds the subscript of * +// the range's starting element, and last holds the subscript * +// of the ranges's last element. The paramter value holds the * +// the search value. If the search value is found, its array * +// subscript is returned. Otherwise, -1 is returned indicating * +// the value was not in the array. * +//*************************************************************** + +int binarySearch(int array[], int first, int last, int value) +{ + int middle; // Mid point of search + + if (first > last) + return -1; + middle = (first + last)/2; + if (array[middle]==value) + return middle; + if (array[middle] +using namespace std; + +// Stack template +template +class BinaryTree +{ +private: + struct TreeNode + { + T value; // The value in the node + TreeNode *left; // Pointer to left child node + TreeNode *right; // Pointer to right child node + }; + + TreeNode *root; // Pointer to the root node + + // Private member functions + void insert(TreeNode *&, TreeNode *&); + void destroySubTree(TreeNode *); + void deleteNode(T, TreeNode *&); + void makeDeletion(TreeNode *&); + void displayInOrder(TreeNode *) const; + void displayPreOrder(TreeNode *) const; + void displayPostOrder(TreeNode *) const; + +public: + // Constructor + BinaryTree() + { root = nullptr; } + + // Destructor + ~BinaryTree() + { destroySubTree(root); } + + // Binary tree operations + void insertNode(T); + bool searchNode(T); + void remove(T); + + void displayInOrder() const + { displayInOrder(root); } + + void displayPreOrder() const + { displayPreOrder(root); } + + void displayPostOrder() const + { displayPostOrder(root); } +}; + +//************************************************************* +// insert accepts a TreeNode pointer and a pointer to a node. * +// The function inserts the node into the tree pointed to by * +// the TreeNode pointer. This function is called recursively. * +//************************************************************* +template +void BinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) +{ + if (nodePtr == nullptr) + nodePtr = newNode; // Insert the node. + else if (newNode->value < nodePtr->value) + insert(nodePtr->left, newNode); // Search the left branch + else + insert(nodePtr->right, newNode); // Search the right branch +} + +//********************************************************** +// insertNode creates a new node to hold num as its value, * +// and passes it to the insert function. * +//********************************************************** +template +void BinaryTree::insertNode(T item) +{ + TreeNode *newNode = nullptr; // Pointer to a new node. + + // Create a new node and store num in it. + newNode = new TreeNode; + newNode->value = item; + newNode->left = newNode->right = nullptr; + + // Insert the node. + insert(root, newNode); +} + +//*************************************************** +// destroySubTree is called by the destructor. It * +// deletes all nodes in the tree. * +//*************************************************** +template +void BinaryTree::destroySubTree(TreeNode *nodePtr) +{ + if (nodePtr) + { + if (nodePtr->left) + destroySubTree(nodePtr->left); + if (nodePtr->right) + destroySubTree(nodePtr->right); + delete nodePtr; + } +} + +//*************************************************** +// searchNode determines if a value is present in * +// the tree. If so, the function returns true. * +// Otherwise, it returns false. * +//*************************************************** +template +bool BinaryTree::searchNode(T item) +{ + TreeNode *nodePtr = root; + + while (nodePtr) + { + if (nodePtr->value == item) + return true; + else if (item < nodePtr->value) + nodePtr = nodePtr->left; + else + nodePtr = nodePtr->right; + } + return false; +} + +//********************************************** +// remove calls deleteNode to delete the * +// node whose value member is the same as num. * +//********************************************** +template +void BinaryTree::remove(T item) +{ + deleteNode(item, root); +} + +//******************************************** +// deleteNode deletes the node whose value * +// member is the same as num. * +//******************************************** +template +void BinaryTree::deleteNode(T item, TreeNode *&nodePtr) +{ + if (item < nodePtr->value) + deleteNode(item, nodePtr->left); + else if (item > nodePtr->value) + deleteNode(item, nodePtr->right); + else + makeDeletion(nodePtr); +} + +//*********************************************************** +// makeDeletion takes a reference to a pointer to the node * +// that is to be deleted. The node is removed and the * +// branches of the tree below the node are reattached. * +//*********************************************************** +template +void BinaryTree::makeDeletion(TreeNode *&nodePtr) +{ + // Define a temporary pointer to use in reattaching + // the left subtree. + TreeNode *tempNodePtr = nullptr; + + if (nodePtr == nullptr) + cout << "Cannot delete empty node.\n"; + else if (nodePtr->right == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->left; // Reattach the left child + delete tempNodePtr; + } + else if (nodePtr->left == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->right; // Reattach the right child + delete tempNodePtr; + } + // If the node has two children. + else + { + // Move one node the right. + tempNodePtr = nodePtr->right; + // Go to the end left node. + while (tempNodePtr->left) + tempNodePtr = tempNodePtr->left; + // Reattach the left subtree. + tempNodePtr->left = nodePtr->left; + tempNodePtr = nodePtr; + // Reattach the right subtree. + nodePtr = nodePtr->right; + delete tempNodePtr; + } +} + +//**************************************************************** +// The displayInOrder member function displays the values * +// in the subtree pointed to by nodePtr, via inorder traversal. * +//**************************************************************** +template +void BinaryTree::displayInOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayInOrder(nodePtr->left); + cout << nodePtr->value << endl; + displayInOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPreOrder member function displays the values * +// in the subtree pointed to by nodePtr, via preorder traversal. * +//**************************************************************** +template +void BinaryTree::displayPreOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + cout << nodePtr->value << endl; + displayPreOrder(nodePtr->left); + displayPreOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPostOrder member function displays the values * +// in the subtree pointed to by nodePtr, via postorder traversal.* +//**************************************************************** +template +void BinaryTree::displayPostOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayPostOrder(nodePtr->left); + displayPostOrder(nodePtr->right); + cout << nodePtr->value << endl; + } +} +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 20/IntBinaryTree.cpp b/SourceCode/Chapter 20/IntBinaryTree.cpp new file mode 100755 index 0000000..58fa9e4 --- /dev/null +++ b/SourceCode/Chapter 20/IntBinaryTree.cpp @@ -0,0 +1,192 @@ +// Implementation file for the IntBinaryTree class +#include +#include "IntBinaryTree.h" +using namespace std; + +//************************************************************* +// insert accepts a TreeNode pointer and a pointer to a node. * +// The function inserts the node into the tree pointed to by * +// the TreeNode pointer. This function is called recursively. * +//************************************************************* + +void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode) +{ + if (nodePtr == nullptr) + nodePtr = newNode; // Insert the node. + else if (newNode->value < nodePtr->value) + insert(nodePtr->left, newNode); // Search the left branch + else + insert(nodePtr->right, newNode); // Search the right branch +} + +//********************************************************** +// insertNode creates a new node to hold num as its value, * +// and passes it to the insert function. * +//********************************************************** + +void IntBinaryTree::insertNode(int num) +{ + TreeNode *newNode = nullptr; // Pointer to a new node. + + // Create a new node and store num in it. + newNode = new TreeNode; + newNode->value = num; + newNode->left = newNode->right = nullptr; + + // Insert the node. + insert(root, newNode); +} + +//*************************************************** +// destroySubTree is called by the destructor. It * +// deletes all nodes in the tree. * +//*************************************************** + +void IntBinaryTree::destroySubTree(TreeNode *nodePtr) +{ + if (nodePtr) + { + if (nodePtr->left) + destroySubTree(nodePtr->left); + if (nodePtr->right) + destroySubTree(nodePtr->right); + delete nodePtr; + } +} + +//*************************************************** +// searchNode determines if a value is present in * +// the tree. If so, the function returns true. * +// Otherwise, it returns false. * +//*************************************************** + +bool IntBinaryTree::searchNode(int num) +{ + TreeNode *nodePtr = root; + + while (nodePtr) + { + if (nodePtr->value == num) + return true; + else if (num < nodePtr->value) + nodePtr = nodePtr->left; + else + nodePtr = nodePtr->right; + } + return false; +} + +//********************************************** +// remove calls deleteNode to delete the * +// node whose value member is the same as num. * +//********************************************** + +void IntBinaryTree::remove(int num) +{ + deleteNode(num, root); +} + + +//******************************************** +// deleteNode deletes the node whose value * +// member is the same as num. * +//******************************************** + +void IntBinaryTree::deleteNode(int num, TreeNode *&nodePtr) +{ + if (num < nodePtr->value) + deleteNode(num, nodePtr->left); + else if (num > nodePtr->value) + deleteNode(num, nodePtr->right); + else + makeDeletion(nodePtr); +} + + +//*********************************************************** +// makeDeletion takes a reference to a pointer to the node * +// that is to be deleted. The node is removed and the * +// branches of the tree below the node are reattached. * +//*********************************************************** + +void IntBinaryTree::makeDeletion(TreeNode *&nodePtr) +{ + // Define a temporary pointer to use in reattaching + // the left subtree. + TreeNode *tempNodePtr = nullptr; + + if (nodePtr == nullptr) + cout << "Cannot delete empty node.\n"; + else if (nodePtr->right == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->left; // Reattach the left child + delete tempNodePtr; + } + else if (nodePtr->left == nullptr) + { + tempNodePtr = nodePtr; + nodePtr = nodePtr->right; // Reattach the right child + delete tempNodePtr; + } + // If the node has two children. + else + { + // Move one node the right. + tempNodePtr = nodePtr->right; + // Go to the end left node. + while (tempNodePtr->left) + tempNodePtr = tempNodePtr->left; + // Reattach the left subtree. + tempNodePtr->left = nodePtr->left; + tempNodePtr = nodePtr; + // Reattach the right subtree. + nodePtr = nodePtr->right; + delete tempNodePtr; + } +} + +//**************************************************************** +// The displayInOrder member function displays the values * +// in the subtree pointed to by nodePtr, via inorder traversal. * +//**************************************************************** + +void IntBinaryTree::displayInOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayInOrder(nodePtr->left); + cout << nodePtr->value << endl; + displayInOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPreOrder member function displays the values * +// in the subtree pointed to by nodePtr, via preorder traversal. * +//**************************************************************** + +void IntBinaryTree::displayPreOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + cout << nodePtr->value << endl; + displayPreOrder(nodePtr->left); + displayPreOrder(nodePtr->right); + } +} + +//**************************************************************** +// The displayPostOrder member function displays the values * +// in the subtree pointed to by nodePtr, via postorder traversal.* +//**************************************************************** + +void IntBinaryTree::displayPostOrder(TreeNode *nodePtr) const +{ + if (nodePtr) + { + displayPostOrder(nodePtr->left); + displayPostOrder(nodePtr->right); + cout << nodePtr->value << endl; + } +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/IntBinaryTree.h b/SourceCode/Chapter 20/IntBinaryTree.h new file mode 100755 index 0000000..aaf5245 --- /dev/null +++ b/SourceCode/Chapter 20/IntBinaryTree.h @@ -0,0 +1,49 @@ +// Specification file for the IntBinaryTree class +#ifndef INTBINARYTREE_H +#define INTBINARYTREE_H + +class IntBinaryTree +{ +private: + struct TreeNode + { + int value; // The value in the node + TreeNode *left; // Pointer to left child node + TreeNode *right; // Pointer to right child node + }; + + TreeNode *root; // Pointer to the root node + + // Private member functions + void insert(TreeNode *&, TreeNode *&); + void destroySubTree(TreeNode *); + void deleteNode(int, TreeNode *&); + void makeDeletion(TreeNode *&); + void displayInOrder(TreeNode *) const; + void displayPreOrder(TreeNode *) const; + void displayPostOrder(TreeNode *) const; + +public: + // Constructor + IntBinaryTree() + { root = nullptr; } + + // Destructor + ~IntBinaryTree() + { destroySubTree(root); } + + // Binary tree operations + void insertNode(int); + bool searchNode(int); + void remove(int); + + void displayInOrder() const + { displayInOrder(root); } + + void displayPreOrder() const + { displayPreOrder(root); } + + void displayPostOrder() const + { displayPostOrder(root); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-1.cpp b/SourceCode/Chapter 20/Pr20-1.cpp new file mode 100755 index 0000000..8f7ae5c --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-1.cpp @@ -0,0 +1,19 @@ +// This program builds a binary tree with 5 nodes. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + cout << "Inserting nodes. "; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + cout << "Done.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-2.cpp b/SourceCode/Chapter 20/Pr20-2.cpp new file mode 100755 index 0000000..d1f48ce --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-2.cpp @@ -0,0 +1,32 @@ +// This program builds a binary tree with 5 nodes. +// The nodes are displayed with inorder, preorder, +// and postorder algorithms. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + // Insert some nodes. + cout << "Inserting nodes.\n"; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + + // Display inorder. + cout << "Inorder traversal:\n"; + tree.displayInOrder(); + + // Display preorder. + cout << "\nPreorder traversal:\n"; + tree.displayPreOrder(); + + // Display postorder. + cout << "\nPostorder traversal:\n"; + tree.displayPostOrder(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-3.cpp b/SourceCode/Chapter 20/Pr20-3.cpp new file mode 100755 index 0000000..6641af9 --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-3.cpp @@ -0,0 +1,31 @@ +// This program builds a binary tree with 5 nodes. +// The SearchNode function is demonstrated. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + // Insert some nodes in the tree. + cout << "Inserting nodes.\n"; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + + // Search for the value 3. + if (tree.searchNode(3)) + cout << "3 is found in the tree.\n"; + else + cout << "3 was not found in the tree.\n"; + + // Search for the value 100. + if (tree.searchNode(100)) + cout << "100 is found in the tree.\n"; + else + cout << "100 was not found in the tree.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-4.cpp b/SourceCode/Chapter 20/Pr20-4.cpp new file mode 100755 index 0000000..b179e4d --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-4.cpp @@ -0,0 +1,35 @@ +// This program builds a binary tree with 5 nodes. +// The DeleteNode function is used to remove two of them. +#include +#include "IntBinaryTree.h" +using namespace std; + +int main() +{ + IntBinaryTree tree; + + // Insert some values into the tree. + cout << "Inserting nodes.\n"; + tree.insertNode(5); + tree.insertNode(8); + tree.insertNode(3); + tree.insertNode(12); + tree.insertNode(9); + + // Display the values. + cout << "Here are the values in the tree:\n"; + tree.displayInOrder(); + + // Delete the value 8. + cout << "Deleting 8...\n"; + tree.remove(8); + + // Delete the value 12. + cout << "Deleting 12...\n"; + tree.remove(12); + + // Display the values. + cout << "Now, here are the nodes:\n"; + tree.displayInOrder(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/Chapter 20/Pr20-5.cpp b/SourceCode/Chapter 20/Pr20-5.cpp new file mode 100755 index 0000000..e8cafd8 --- /dev/null +++ b/SourceCode/Chapter 20/Pr20-5.cpp @@ -0,0 +1,28 @@ +// This program demonstrates the BinaryTree class template. +// It builds a binary tree with 5 nodes. +#include +#include "BinaryTree.h" +using namespace std; + +const int NUM_NODES = 5; + +int main() +{ + string name; + + // Create the binary tree. + BinaryTree tree; + + // Insert some names. + for (int count = 0; count < NUM_NODES; count++) + { + cout << "Enter an name: "; + getline(cin, name); + tree.insertNode(name); + } + + // Display the values. + cout << "\nHere are the values in the tree:\n"; + tree.displayInOrder(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/MyString.cpp b/SourceCode/case studies/Creating a String Class/MyString.cpp new file mode 100755 index 0000000..226dd39 --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/MyString.cpp @@ -0,0 +1,280 @@ +// Implementation file for the MyString class +#include // For string library functions +#include "MyString.h" +using namespace std; + +//************************************************* +// Overloaded = operator. Called when operand * +// on the right is another MyString object. * +// Returns the calling object. * +//************************************************* + +const MyString MyString::operator=(MyString &right) +{ + if (len != 0) + delete [] str; + str = new char[right.length() + 1]; + strcpy(str, right.getValue()); + len = right.length(); + return *this; +} + +//************************************************* +// Overloaded = operator. Called when operand * +// on the right is a C-string. * +// Returns the str member of the calling object. * +//************************************************* + +const char *MyString::operator=(const char *right) +{ + if (len != 0) + delete [] str; + len = strlen(right); + str = new char[len + 1]; + strcpy(str, right); + return str; +} + +//************************************************* +// Overloaded += operator. Called when operand * +// on the right is another MyString object. * +// Concatenates the str member of right to the * +// str member of the calling object. * +// Returns the calling object. * +//************************************************* + +const MyString MyString::operator+=(MyString &right) +{ + char *temp = str; + + str = new char[strlen(str) + right.length() + 1]; + strcpy(str, temp); + strcat(str, right.getValue()); + if (len != 0) + delete [] temp; + len = strlen(str); + return *this; +} + +//************************************************* +// Overloaded += operator. Called when operand * +// on the right is a string. Concatenates the * +// str member of right to the str member of * +// the calling object. * +// Returns the str member of the calling object. * +//************************************************* + +const char *MyString::operator+=(const char *right) +{ + char *temp = str; + + str = new char[strlen(str) + strlen(right) + 1]; + strcpy(str, temp); + strcat(str, right); + if (len != 0) + delete [] temp; + return str; +} + +//***************************************************** +// Overloaded == operator. * +// Called when the operand on the right is a MyString * +// object. Returns 1 if right.str is the same as str. * +//***************************************************** + +int MyString::operator==(MyString &right) +{ + return !strcmp(str, right.getValue()); +} + +//**************************************************** +// Overloaded == operator. * +// Called when the operand on the right is a string. * +// Returns 1 if right is the same as str. * +//**************************************************** + +int MyString::operator==(const char *right) +{ + return !strcmp(str, right); +} + +//********************************************************* +// Overloaded != operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if right.str is not equal to str. * +//********************************************************* + +int MyString::operator!=(MyString &right) +{ + return strcmp(str, right.getValue()); +} + +//**************************************************** +// Overloaded != operator. * +// Called when the operand on the right is a string. * +// Returns true if right is not equal to str. * +//**************************************************** + +int MyString::operator!=(const char *right) +{ + return strcmp(str, right); +} + +//********************************************************* +// Overloaded > operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if str is greater than right.str. * +//********************************************************* + +bool MyString::operator>(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) > 0) + status = true; + else + status = false; + return status; +} + +//**************************************************** +// Overloaded > operator. * +// Called when the operand on the right is a string. * +// Returns true if str is greater than right. * +//**************************************************** + +bool MyString::operator>(const char *right) +{ + bool status; + + if (strcmp(str, right) > 0) + status = true; + else + status = false; + return status; +} + +//****************************************************** +// Overloaded < operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if str is less than right.str. * +//****************************************************** + +bool MyString::operator<(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) < 0) + status = true; + else + status = false; + return status; +} + +//**************************************************** +// Overloaded < operator. * +// Called when the operand on the right is a string. * +// Returns true if str is less than right. * +//**************************************************** + +bool MyString::operator<(const char *right) +{ + bool status; + + if (strcmp(str, right) < 0) + status = true; + else + status = false; + return status; +} + +//***************************************************** +// Overloaded >= operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if str is greater than or * +// equal to right.str * +//***************************************************** + +bool MyString::operator>=(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) >= 0) + status = true; + else + status = false; + return status; +} + +//********************************************************* +// Overloaded >= operator. * +// Called when the operand on the right is a string. * +// Returns true if str is greater than or equal to right. * +//********************************************************* + +bool MyString::operator>=(const char *right) +{ + bool status; + + if (strcmp(str, right) >= 0) + status = true; + else + status = false; + return status; +} + +//********************************************************** +// Overloaded <= operator. * +// Called when the operand on the right is a MyString * +// object. Returns true if right.str is less than or equal * +// to right.str. * +//********************************************************** + +bool MyString::operator<=(MyString &right) +{ + bool status; + + if (strcmp(str, right.getValue()) <= 0) + status = true; + else + status = false; + return status; +} + +//****************************************************** +// Overloaded <= operator. * +// Called when the operand on the right is a string. * +// Returns true if str is less than or equal to right. * +//****************************************************** + +bool MyString::operator<=(const char *right) +{ + bool status; + + if (strcmp(str, right) <= 0) + status = true; + else + status = false; + return status; +} + +//************************************************* +// Overloaded stream insertion operator (<<). * +//************************************************* + +ostream &operator<<(ostream &strm, const MyString &obj) +{ + strm << obj.str; + return strm; +} + +//************************************************* +// Overloaded stream extraction operator (>>). * +//************************************************* + +istream &operator>>(istream &strm, MyString &obj) +{ + strm.getline(obj.str, obj.len); + strm.ignore(); + return strm; +} \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/MyString.h b/SourceCode/case studies/Creating a String Class/MyString.h new file mode 100755 index 0000000..ddf98ce --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/MyString.h @@ -0,0 +1,71 @@ +// Specification file for the MyString class +#ifndef MYSTRING_H +#define MYSTRING_H +#include +using namespace std; + +class MyString; // Forward declaration. +ostream &operator<<(ostream &, const MyString &); +istream &operator>>(istream &, MyString &); + +// MyString class. An abstract data type for handling strings. + +class MyString +{ +private: + char *str; + int len; +public: + // Default constructor + MyString() + { str = '\0'; len = 0; } + + // Copy constructor + MyString(MyString &right) + { str = new char[right.length() + 1]; + strcpy(str, right.getValue()); + len = right.length(); } + + // The following constructor initializes the + // MyString object with a C-string + MyString(char *sptr) + { len = strlen(sptr); + str = new char[len + 1]; + strcpy(str, sptr); } + + // Destructor + ~MyString() + { if (len != 0) delete [] str; } + + // The length function returns the string length. + int length() const + { return len; } + + // The getValue function returns the string. + const char *getValue() const + { return str; }; + + // Overloaded operators + const MyString operator+=(MyString &); + const char *operator+=(const char *); + const MyString operator=(MyString &); + const char *operator=(const char *); + int operator==(MyString &); + int operator==(const char *); + int operator!=(MyString &); + int operator!=(const char *); + bool operator>(MyString &); + bool operator>(const char *); + bool operator<(MyString &); + bool operator<(const char *); + bool operator>=(MyString &); + bool operator>=(const char*); + bool operator<=(MyString &); + bool operator<=(const char *); + + // Friends + friend ostream &operator<<(ostream &, const MyString &); + friend istream &operator>>(istream &, MyString &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/Program 14-18.cpp b/SourceCode/case studies/Creating a String Class/Program 14-18.cpp new file mode 100755 index 0000000..f3a9116 --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/Program 14-18.cpp @@ -0,0 +1,37 @@ +// This program demonstrates the MyString class. +#include +#include "MyString.h" + +int main() +{ + // Define and initialize several MyString objects. + MyString object1("This"), object2("is"); + MyString object3("a test."); + MyString object4 = object1; + MyString object5("is only a test."); + // Define a C-string. + char string1[] = "a test."; + + // Display the MyString objects. + cout << "object1: " << object1 << endl; + cout << "object2: " << object2 << endl; + cout << "object3: " << object3 << endl; + cout << "object4: " << object4 << endl; + cout << "object5: " << object5 << endl; + + // Display the C-string. + cout << "string1: " << string1 << endl; + + // Test the overloaded += operator. + object1 += " "; + object1 += object2; + object1 += " "; + object1 += object3; + object1 += " "; + object1 += object4; + object1 += " "; + object1 += object5; + cout << "object1: " << object1 << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/Creating a String Class/Program 14-19.cpp b/SourceCode/case studies/Creating a String Class/Program 14-19.cpp new file mode 100755 index 0000000..fd9f36a --- /dev/null +++ b/SourceCode/case studies/Creating a String Class/Program 14-19.cpp @@ -0,0 +1,62 @@ +// This program demonstrates the MyString class. +#include +#include "MyString.h" +using namespace std; + +int main() +{ + // Define several MyString objects. + MyString name1("Billy"), name2("Sue"); + MyString name3("joe"); + MyString string1("ABC"), string2("DEF"); + + // Display the MyString object values. + cout << "name1: " << name1.getValue() << endl; + cout << "name2: " << name2.getValue() << endl; + cout << "name3: " << name3.getValue() << endl; + cout << "string1: " << string1.getValue() << endl; + cout << "string2: " << string2.getValue() << endl; + + // Test the overloaded relational operators. + if (name1 == name2) + cout << "name1 is equal to name2.\n"; + else + cout << "name1 is not equal to name2.\n"; + + if (name3 == "joe") + cout << "name3 is equal to joe.\n"; + else + cout << "name3 is not equal to joe.\n"; + + if (string1 > string2) + cout << "string1 is greater than string2.\n"; + else + cout << "string1 is not greater than string2.\n"; + + if (string1 < string2) + cout << "string1 is less than string2.\n"; + else + cout << "string1 is not less than string2.\n"; + + if (string1 >= string2) + cout << "string1 is greater than or equal to string2.\n"; + else + cout << "string1 is not greater than or equal to string2.\n"; + + if (string1 >= "ABC") + cout << "string1 is greater than or equal to ABC.\n"; + else + cout << "string1 is not greater than or equal to ABC.\n"; + + if (string1 <= string2) + cout << "string1 is less than or equal to string2.\n"; + else + cout << "string1 is not less than or equal to string2.\n"; + + if (string2 <= "DEF") + cout << "string2 is less than or equal to DEF.\n"; + else + cout << "string2 is not less than or equal to DEF.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 1/Program 6-31.cpp b/SourceCode/case studies/High Adventure Travel Agency - Part 1/Program 6-31.cpp new file mode 100755 index 0000000..113b424 --- /dev/null +++ b/SourceCode/case studies/High Adventure Travel Agency - Part 1/Program 6-31.cpp @@ -0,0 +1,266 @@ +// This program will assist the High Adventure Travel Agency +// in calculating the costs of their 4 major vacation packages. +#include +#include +using namespace std; + +// Constants for the charges. +const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse +const double SCUBA_RATE = 1000.0; // Base rate - Bahamas +const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving +const double CAVE_RATE = 700.0; // Base rate - Spelunking +const double CLIMB_INSTRUCT = 100.0; // Climbing instruction +const double SCUBA_INSTRUCT = 100.0; // Scuba instruction +const double DAILY_CAMP_RENTAL = 40.0; // Daily camping equipment rental +const double DAY_LODGE_1 = 65.0; // Lodging option (sky diving) +const double DAY_LODGE_2 = 120.0; // Lodging option (sky diving) + +// Function prototypes +void climbing(); +void scuba(); +void skyDive(); +void spelunk(); +int menu(); + +int main() +{ + int selection; + + cout << fixed << showpoint << setprecision(2); + do + { + selection = menu(); + switch (selection) + { + case 1: climbing(); + break; + case 2: scuba(); + break; + case 3: skyDive(); + break; + case 4: spelunk(); + break; + case 5: cout << "Exiting program.\n\n"; + } + } while (selection != 5); + return 0; +} + +//****************************************************** +// Definition of function menu. * +// Displays the main menu and asks the user to select * +// an option. Returns an integer in the range 1 - 5. * +//****************************************************** + +int menu() +{ + int choice; + + cout << "High Adventure Travel Agency\n"; + cout << "----------------------------\n"; + cout << "1) Devil's Courthouse Adventure Weekend\n"; + cout << "2) Scuba Bahama\n"; + cout << "3) Sky Dive Colorado\n"; + cout << "4) Barron Cliff Spelunk\n"; + cout << "5) Exit Program\n\n"; + cout << "Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + while (choice < 1 || choice > 5) // Validate input + { + cout << "Invalid Selection. Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + } + return choice; +} + +//************************************************* +// Definition of climbing function. * +// This function calculates the charges for the * +// Devil's Courthouse Adventure Weekend package. * +//************************************************* + +void climbing() +{ + int beginners, // Those needing instruction + advanced, // Those not needing instruction + needEquip; // Those renting camping equipment + double baseCharges, // Base charges + charges, // Total charges + instruction, // Cost of instruction + equipment, // Cost of equipment rental + discount = 0, // Discount + deposit; // Required deposit + + cout << "\nDevil's Courthouse Adventure Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> beginners; + cout << "How many advanced climbers will be going? "; + cin >> advanced; + cout << "How many will rent camping equipment? "; + cin >> needEquip; + // Calculate the base charges. + baseCharges = (beginners + advanced) * CLIMB_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if ((beginners + advanced) > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Add cost of instruction. + instruction = beginners * CLIMB_INSTRUCT; + charges += instruction; + // Add cost of camping equipment rental. + equipment = needEquip * DAILY_CAMP_RENTAL * 4; + charges += equipment; + // Calculate required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << (beginners + advanced); + cout << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Instruction cost: $" << instruction << endl; + cout << "Equipment Rental: $" << equipment << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} + +//************************************************ +// Definition of scuba function. * +// This function calculates the charges for the * +// Scuba Bahama package. * +//************************************************ + +void scuba() +{ + int beginners, // Those needing instruction + advanced; // Those not needing instruction + double baseCharges, // Base charges + charges, // Total charges + instruction, // Cost of instruction + discount = 0, // Discount + deposit; // Required deposit + + cout << "\nScuba Bahama\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> beginners; + cout << "How many advanced scuba divers will be going? "; + cin >> advanced; + // Calculate base charges. + baseCharges = (beginners + advanced) * SCUBA_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if ((beginners + advanced) > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Add cost of instruction. + instruction = beginners * SCUBA_INSTRUCT; + charges += instruction; + + // Calcuate the required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << (beginners + advanced); + cout << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Instruction cost: $" << instruction << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} + +//************************************************ +// Definition of skyDive function. * +// This function calculates the charges for the * +// Sky Dive Colorado package. * +//************************************************ + +void skyDive() +{ + int party, // Number in party + lodge1, // Number at 1st lodging choice + lodge2; // Number at 2nd lodging choice + double baseCharges, // Base charges + charges, // Total charges + discount = 0, // Discount + lodging, // Cost of lodging + deposit; // Required deposit + + cout << "\nSky Dive Colorado\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> party; + // Calculate base charges. + baseCharges = party * SKY_DIVE_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if (party > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Calculate lodging costs. + cout << "How many will stay at Wilderness Lodge? "; + cin >> lodge1; + cout << "How many will stay at Luxury Inn? "; + cin >> lodge2; + lodging = (lodge1 * DAY_LODGE_1) + (lodge2 * DAY_LODGE_2); + charges += lodging; + + // Calculate required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << party << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Lodging: $" << lodging << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} + +//************************************************ +// Definition of spelunk function. * +// This function calculates the charges for the * +// Barron Cliff Spelunk package. * +//************************************************ + +void spelunk() +{ + int party, // Number in party + needEquip; // Those renting camping equipment + double baseCharges, // Base charges + charges, // Total charges + equipment, // Cost of equipment rental + discount = 0, // Discount + deposit; // Required deposit + + cout << "\nBarron Cliff Spelunk Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> party; + cout << "How many will rent camping equipment? "; + cin >> needEquip; + // Calculate base charges. + baseCharges = party * CAVE_RATE; + charges = baseCharges; + // Calculate 10% discount for 5 or more. + if (party > 4) + { + discount = (charges * .1); + charges -= discount; + } + // Add cost of camping equipment rental + equipment = needEquip * DAILY_CAMP_RENTAL * 4; + charges += equipment; + + // Calculate required deposit. + deposit = charges / 2.0; + cout << "Number in party: " << party << endl; + cout << "Base charges: $" << baseCharges << endl; + cout << "Equipment Rental: $" << equipment << endl; + cout << "Discount: $" << discount << endl; + cout << "Total Charges: $" << charges << endl; + cout << "Required Deposit: $" << deposit << endl << endl; +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 2/Program 11-15.cpp b/SourceCode/case studies/High Adventure Travel Agency - Part 2/Program 11-15.cpp new file mode 100755 index 0000000..d8ee18a --- /dev/null +++ b/SourceCode/case studies/High Adventure Travel Agency - Part 2/Program 11-15.cpp @@ -0,0 +1,430 @@ +// This program will assist the High Adventure Travel Agency +// in calculating the costs of their 4 major vacation packages. +// In this version of the program, the data structures needed +// to store the information in a database will be designed. +// The next modification will implement the file operations. +#include +#include +using namespace std; + +// The data structures + +struct Package1 // Climbing Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package2 // Scuba Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package3 // Sky Diving Package +{ + int num; // Number in party + int lodge1; // number at 1st lodging choice + int lodge2; // number at 2nd lodging choice + double baseCharges; // Base charges + double charges; // Total charges + double discount; // Discount + double lodging; // Cost of lodging + double deposit; // Required deposit +}; + +struct Package4 // Spelunking Package +{ + int num; // Number in party + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +union Pack // Combines the four structs +{ + struct Package1 climb; + struct Package2 scuba; + struct Package3 sky; + struct Package4 spel; +}; + +struct Reservation +{ + int packNum; // Indicates which package is stored + union Pack packs; +}; + +// Constants for the charges. +const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse +const double SCUBA_RATE = 1000.0; // Base rate - Bahamas +const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving +const double CAVE_RATE = 700.0; // Base rate - Spelunking +const double CLIMB_INSTRUCT = 100.0; // Climbing instruction +const double SCUBA_INSTRUCT = 100.0; // Scuba instruction +const double DAILY_CAMP_RENTAL = 40.0; // Daily camping equip. rental +const double DAY_LODGE_1 = 65.0; // Lodging option (sky diving) +const double DAY_LODGE_2 = 120.0; // Lodging option (sky diving) + +// Function prototypes +void climbing(Reservation &); +void scuba(Reservation &); +void skyDive(Reservation &); +void spelunk(Reservation &); +int menu(); +void displayInfo(const Reservation &); +void displayPack1(const Reservation &); +void displayPack2(const Reservation &); +void displayPack3(const Reservation &); +void displayPack4(const Reservation &); + +int main() +{ + int selection; + Reservation group; + + cout << fixed << showpoint << setprecision(2); + do + { + selection = menu(); + switch(selection) + { + case 1 : climbing(group); + break; + case 2 : scuba(group); + break; + case 3 : skyDive(group); + break; + case 4 : spelunk(group); + break; + case 5 : cout << "Exiting program.\n\n"; + } + if (selection < 5) + displayInfo(group); + } while (selection != 5); + return 0; +} + +//***************************************************** +// Definition of function menu. * +// Displays the main menu and asks the user to select * +// an option. Returns an integer in the range 1 - 5. * +//***************************************************** + +int menu() +{ + int choice; + + cout << "High Adventure Travel Agency\n"; + cout << "----------------------------\n"; + cout << "1) Devil's Courthouse Adventure Weekend\n"; + cout << "2) Scuba Bahama\n"; + cout << "3) Sky Dive Colorado\n"; + cout << "4) Barron Cliff Spelunk\n"; + cout << "5) Exit Program\n\n"; + cout << "Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + while (choice < 1 || choice > 5) // Validate input + { + cout << "Invalid Selection. Enter 1, 2, 3, 4, or 5: "; + cin >> choice; + } + return choice; +} + +//****************************************************** +// Definition of climbing function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Devil's Courthouse Adventure Weekend package. * +//****************************************************** + +void climbing(Reservation &group) +{ + group.packNum = 1; + cout << "\nDevil's Courthouse Adventure Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.climb.beginners; + cout << "How many advanced climbers will be going? "; + cin >> group.packs.climb.advanced; + group.packs.climb.num = group.packs.climb.beginners + + group.packs.climb.advanced; + cout << "How many will rent camping equipment? "; + cin >> group.packs.climb.needEquip; + // Calculate base charges. + group.packs.climb.baseCharges = group.packs.climb.num * + CLIMB_RATE; + group.packs.climb.charges = group.packs.climb.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.climb.num > 4) + { + group.packs.climb.discount = group.packs.climb.charges + * .1; + group.packs.climb.charges -= group.packs.climb.discount; + } + else + group.packs.climb.discount = 0; + // Add cost of instruction. + group.packs.climb.instruction = group.packs.climb.beginners + * CLIMB_INSTRUCT; + group.packs.climb.charges += group.packs.climb.instruction; + // Add cost of camping equipment rental + group.packs.climb.equipment = group.packs.climb.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.climb.charges += group.packs.climb.equipment; + // Calculate required deposit. + group.packs.climb.deposit = group.packs.climb.charges / 2.0; +} + +//****************************************************** +// Definition of scuba function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Scuba Bahama package. * +//****************************************************** + +void scuba(Reservation &group) +{ + group.packNum = 2; + cout << "\nScuba Bahama\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.scuba.beginners; + cout << "How many advanced scuba divers will be going? "; + cin >> group.packs.scuba.advanced; + group.packs.scuba.num = group.packs.scuba.beginners + + group.packs.scuba.advanced; + // Calculate base charges. + group.packs.scuba.baseCharges = group.packs.scuba.num * + SCUBA_RATE; + group.packs.scuba.charges = group.packs.scuba.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.scuba.num > 4) + { + group.packs.scuba.discount = group.packs.scuba.charges + * .1; + group.packs.scuba.charges -= group.packs.scuba.discount; + } + else + group.packs.scuba.discount = 0; + // Add cost of instruction. + group.packs.scuba.instruction = group.packs.scuba.beginners + * SCUBA_INSTRUCT; + group.packs.scuba.charges += group.packs.scuba.instruction; + // Calculate required deposit. + group.packs.scuba.deposit = group.packs.scuba.charges / 2.0; +} + +//****************************************************** +// Definition of skyDive function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Sky Dive Colorado package. * +//****************************************************** + +void skyDive(Reservation &group) +{ + group.packNum = 3; + cout << "\nSky Dive Colorado\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.sky.num; + // Calculate base charges. + group.packs.sky.baseCharges = group.packs.sky.num + * SKY_DIVE_RATE; + group.packs.sky.charges = group.packs.sky.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.sky.num > 4) + { + group.packs.sky.discount = group.packs.sky.charges * .1; + group.packs.sky.charges -= group.packs.sky.discount; + } + else + group.packs.sky.discount = 0; + // Calculate lodging costs. + cout << "How may will stay at Wilderness Lodge? "; + cin >> group.packs.sky.lodge1; + cout << "How many will stay at Luxury Inn? "; + cin >> group.packs.sky.lodge2; + group.packs.sky.lodging = (group.packs.sky.lodge1 * + DAY_LODGE_1) + (group.packs.sky.lodge2 * + DAY_LODGE_2); + // Calculate required deposit. + group.packs.sky.deposit = group.packs.sky.charges / 2.0; +} + +//****************************************************** +// Definition of spelunk function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Barron Cliff Spelunk package. * +//****************************************************** + +void spelunk(Reservation &group) +{ + group.packNum = 4; + cout << "\nBarron Cliff Spelunk Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.spel.num; + cout << "How many will rent camping equipment? "; + cin >> group.packs.spel.needEquip; + // Calculate base charges. + group.packs.spel.baseCharges = group.packs.spel.num * + CAVE_RATE; + group.packs.spel.charges = group.packs.spel.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.spel.num > 4) + { + group.packs.spel.discount = group.packs.spel.charges * .1; + group.packs.spel.charges -= group.packs.spel.discount; + } + else + group.packs.spel.discount = 0; + // Add cost of camping equipment rental + group.packs.spel.equipment = group.packs.spel.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.spel.charges += group.packs.spel.equipment; + // Calculate required deposit. + group.packs.spel.deposit = group.packs.spel.charges / 2.0; +} + +//************************************************************** +// Definition of function displayInfo. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function looks in the * +// group.packNum member to determine which function to call * +// to display the vacation package information. * +//************************************************************** + +void displayInfo(const Reservation &group) +{ + switch (group.packNum) + { + case 1: displayPack1(group); + break; + case 2: displayPack2(group); + break; + case 3: displayPack3(group); + break; + case 4: displayPack4(group); + break; + default: cout << "ERROR: Invalid package number.\n"; + } +} + +//************************************************************** +// Definition of function displayPack1. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 1. * +//************************************************************** + +void displayPack1(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.climb.num << endl; + cout << "Base charges: $" + << group.packs.climb.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.climb.instruction << endl; + cout << "Equipment Rental: $" + << group.packs.climb.equipment << endl; + cout << "Discount: $" + << group.packs.climb.discount << endl; + cout << "Total charges: $" + << group.packs.climb.charges << endl; + cout << "Required deposit: $" + << group.packs.climb.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack2. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 2. * +//************************************************************** + +void displayPack2(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.scuba.num << endl; + cout << "Base charges: $" + << group.packs.scuba.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.scuba.instruction << endl; + cout << "Discount: $" + << group.packs.scuba.discount << endl; + cout << "Total Charges: $" + << group.packs.scuba.charges << endl; + cout << "Required deposit: $" + << group.packs.scuba.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack3. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 3. * +//************************************************************** + +void displayPack3(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.sky.num << endl; + cout << "Base charges: $" + << group.packs.sky.baseCharges << endl; + cout << "Lodging: $" + << group.packs.sky.lodging << endl; + cout << "Discount: $" + << group.packs.sky.discount << endl; + cout << "Total Charges: $" + << group.packs.sky.charges << endl; + cout << "Required deposit: $" + << group.packs.sky.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack4. * +// Uses a constant Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 4. * +//************************************************************** + +void displayPack4(const Reservation &group) +{ + cout << "Number in party: " + << group.packs.spel.num << endl; + cout << "Base charges: $" + << group.packs.spel.baseCharges << endl; + cout << "Equipment Rental: $" + << group.packs.spel.equipment << endl; + cout << "Discount: $" + << group.packs.spel.discount << endl; + cout << "Total Charges: $" + << group.packs.spel.charges << endl; + cout << "Required deposit: $" + << group.packs.spel.deposit << endl << endl; +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 3/Program 12-23.cpp b/SourceCode/case studies/High Adventure Travel Agency - Part 3/Program 12-23.cpp new file mode 100755 index 0000000..59465a7 --- /dev/null +++ b/SourceCode/case studies/High Adventure Travel Agency - Part 3/Program 12-23.cpp @@ -0,0 +1,533 @@ +// This program will assist the High Adventure Travel Agency +// in booking reservations for any of their 4 major +// vacation packages. +#include +#include +#include +#include +using namespace std; + +// Data Structures +struct Package1 // Climbing Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package2 // Scuba Package +{ + int num; // Number in party + int beginners; // Those needing instruction + int advanced; // Those not needing instruction + double baseCharges; // Base charges + double charges; // Total charges + double instruction; // Cost of instruction + double discount; // Discount + double deposit; // Required deposit +}; + +struct Package3 // Sky Diving Package +{ + int num; // Number in party + int lodge1; // Number at 1st lodging choice + int lodge2; // Number at 2nd lodging choice + double baseCharges; // Base charges + double charges; // Total charges + double discount; // Discount + double lodging; // Cost of lodging + double deposit; // Required deposit +}; + +struct Package4 // Spelunking Package +{ + int num; // Number in party + int needEquip; // Those renting camping equipment + double baseCharges; // Base charges + double charges; // Total charges + double equipment; // Cost of equipment rental + double discount; // Discount + double deposit; // Required deposit +}; + +union Pack +{ + struct Package1 climb; + struct Package2 scuba; + struct Package3 sky; + struct Package4 spel; +}; + +struct Reservation +{ + int packNum; + union Pack packs; +}; + +// Constants for the charges. +const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse +const double SCUBA_RATE = 1000.0; // Base rate - Bahamas +const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving +const double CAVE_RATE = 700.0; // Base rate - Spelunking +const double CLIMB_INSTRUCT = 100.0; // Climbing instruction +const double SCUBA_INSTRUCT = 100.0; // Scuba instruction +const double DAILY_CAMP_RENTAL = 40.0; // Daily camping equip. rental +const double DAY_LODGE_1 = 65.0; // Lodging option (sky diving) +const double DAY_LODGE_2 = 120.0; // Lodging option (sky diving) + +// Function prototypes +void openFile(fstream &); +void saveInfo(Reservation &, fstream &); +void climbing(Reservation &); +void scuba(Reservation &); +void skyDive(Reservation &); +void spelunk(Reservation &); +int menu(); +void displayInfo(Reservation &); +void displayPack1(Reservation &); +void displayPack2(Reservation &); +void displayPack3(Reservation &); +void displayPack4(Reservation &); +void showRes(fstream &); + +int main() +{ + int selection; + Reservation group; + fstream file; + + cout << fixed << showpoint << setprecision(2); + openFile(file); + do + { + selection = menu(); + switch(selection) + { + case 1 : climbing(group); + break; + case 2 : scuba(group); + break; + case 3 : skyDive(group); + break; + case 4 : spelunk(group); + break; + case 5 : showRes(file); + break; + case 6 : cout << "Exiting program.\n\n"; + } + if (selection < 5) + { + displayInfo(group); + saveInfo(group, file); + } + } while (selection != 6); + file.close(); + return 0; +} + +//************************************************** +// Definition of function openFile. * +// Accepts an fstream object as an argument. The * +// file is opened for both input and output, in * +// binary mode. * +//************************************************** + +void openFile(fstream &file) +{ + const int SIZE = 256; + char fileName[SIZE]; + + cout << "File name: "; + cin.getline(fileName, SIZE); + + file.open(fileName, ios::in | ios::out | ios::binary); + if (!file) + { + cout << "Creating " << fileName << "...\n"; + // Create the file. + file.open(fileName, ios::out); + // Close the file. + file.close(); + // Reopen the file for input and output. + file.open(fileName, ios::in | ios::out | ios::binary); + } +} + +//************************************************************ +// Definition of function saveInfo. * +// Accepts a Reservation structure and an fstream object. * +// The user is asked if the data in the structure * +// is to be saved. If so, it is saved at the end of the file.* +//************************************************************ + +void saveInfo(Reservation &group, fstream &file) +{ + char yorN; + + cout << "Do you want to save this data? (Y/N) "; + cin >> yorN; + yorN = toupper(yorN); + + // Validate input + while (yorN != 'Y' && yorN != 'N') + { + cout << "Please enter Y or N\n"; + cin >> yorN; + yorN = toupper(yorN); + } + + // Save the data. + if (yorN == 'Y') + { + cout << "Saving reservation data.\n"; + file.write(reinterpret_cast(&group), sizeof(group)); + if (!file) + cout << "Could not write to file!\n"; + } +} + +//***************************************************** +// Definition of function menu. * +// Displays the main menu and asks the user to select * +// an option. Returns an integer in the range 1 - 6. * +//***************************************************** + +int menu( ) +{ + int choice; + + cout << "High Adventure Travel Agency\n"; + cout << "----------------------------\n"; + cout << "1) Devil's Courthouse Adventure Weekend\n"; + cout << "2) Scuba Bahama\n"; + cout << "3) Sky Dive Colorado\n"; + cout << "4) Barron Cliff Spelunk\n"; + cout << "5) Show Booked Reservations\n"; + cout << "6) Exit Program\n\n"; + cout << "Enter 1, 2, 3, 4, 5, or 6: "; + cin >> choice; + + while (choice < 1 || choice > 6) + { + cout << "Invalid Selection\n"; + cin >> choice; + } + return choice; +} + +//****************************************************** +// Definition of climbing function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Devil's Courthouse Adventure Weekend package. * +//****************************************************** + +void climbing(Reservation &group) +{ + group.packNum = 1; + cout << "\nDevil's Courthouse Adventure Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.climb.beginners; + cout << "How many advanced climbers will be going? "; + cin >> group.packs.climb.advanced; + group.packs.climb.num = group.packs.climb.beginners + + group.packs.climb.advanced; + cout << "How many will rent camping equipment? "; + cin >> group.packs.climb.needEquip; + // Calculate base charges. + group.packs.climb.baseCharges = group.packs.climb.num * + CLIMB_RATE; + group.packs.climb.charges = group.packs.climb.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.climb.num > 4) + { + group.packs.climb.discount = group.packs.climb.charges + * .1; + group.packs.climb.charges -= group.packs.climb.discount; + } + else + group.packs.climb.discount = 0; + // Add cost of instruction. + group.packs.climb.instruction = group.packs.climb.beginners + * CLIMB_INSTRUCT; + group.packs.climb.charges += group.packs.climb.instruction; + // Add cost of camping equipment rental + group.packs.climb.equipment = group.packs.climb.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.climb.charges += group.packs.climb.equipment; + // Calculate required deposit. + group.packs.climb.deposit = group.packs.climb.charges / 2.0; +} + +//****************************************************** +// Definition of scuba function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Scuba Bahama package. * +//****************************************************** + +void scuba(Reservation &group) +{ + group.packNum = 2; + cout << "\nScuba Bahama\n"; + cout << "------------------------------------\n"; + cout << "How many will be going who need an instructor? "; + cin >> group.packs.scuba.beginners; + cout << "How many advanced scuba divers will be going? "; + cin >> group.packs.scuba.advanced; + group.packs.scuba.num = group.packs.scuba.beginners + + group.packs.scuba.advanced; + // Calculate base charges. + group.packs.scuba.baseCharges = group.packs.scuba.num * + SCUBA_RATE; + group.packs.scuba.charges = group.packs.scuba.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.scuba.num > 4) + { + group.packs.scuba.discount = group.packs.scuba.charges + * .1; + group.packs.scuba.charges -= group.packs.scuba.discount; + } + else + group.packs.scuba.discount = 0; + // Add cost of instruction. + group.packs.scuba.instruction = group.packs.scuba.beginners + * SCUBA_INSTRUCT; + group.packs.scuba.charges += group.packs.scuba.instruction; + // Calculate required deposit. + group.packs.scuba.deposit = group.packs.scuba.charges / 2.0; +} + +//****************************************************** +// Definition of skyDive function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Sky Dive Colorado package. * +//****************************************************** + +void skyDive(Reservation &group) +{ + group.packNum = 3; + cout << "\nSky Dive Colorado\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.sky.num; + // Calculate base charges. + group.packs.sky.baseCharges = group.packs.sky.num * + SKY_DIVE_RATE; + group.packs.sky.charges = group.packs.sky.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.sky.num > 4) + { + group.packs.sky.discount = group.packs.sky.charges * .1; + group.packs.sky.charges -= group.packs.sky.discount; + } + else + group.packs.sky.discount = 0; + // Calculate lodging costs. + cout << "How may will stay at Wilderness Lodge? "; + cin >> group.packs.sky.lodge1; + cout << "How many will stay at Luxury Inn? "; + cin >> group.packs.sky.lodge2; + group.packs.sky.lodging = (group.packs.sky.lodge1 * + DAY_LODGE_1) + (group.packs.sky.lodge2 * DAY_LODGE_2); + group.packs.sky.charges += group.packs.sky.lodging; + // Calculate required deposit. + group.packs.sky.deposit = group.packs.sky.charges / 2.0; +} + +//****************************************************** +// Definition of spelunk function. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. * +// This function calculates the charges for the * +// Barron Cliff Spelunk package. * +//****************************************************** + +void spelunk(Reservation &group) +{ + group.packNum = 4; + cout << "\nBarron Cliff spelunk Weekend\n"; + cout << "------------------------------------\n"; + cout << "How many will be going? "; + cin >> group.packs.spel.num; + cout << "How many will rent camping equipment? "; + cin >> group.packs.spel.needEquip; + // Calculate base charges. + group.packs.spel.baseCharges = group.packs.spel.num * + CAVE_RATE; + group.packs.spel.charges = group.packs.spel.baseCharges; + // Calculate 10% discount for 5 or more. + if (group.packs.spel.num > 4) + { + group.packs.spel.discount = group.packs.spel.charges * .1; + group.packs.spel.charges -= group.packs.spel.discount; + } + else + group.packs.spel.discount = 0; + // Add cost of camping equipment rental + group.packs.spel.equipment = group.packs.spel.needEquip * + DAILY_CAMP_RENTAL * 4; + group.packs.spel.charges += group.packs.spel.equipment; + // Calculate required deposit. + group.packs.spel.deposit = group.packs.spel.charges / 2.0; +} + +//************************************************************** +// Definition of function displayInfo. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function looks in the * +// group.packNum member to determine which function to call * +// to display the vacation package information. * +//************************************************************** + +void displayInfo(Reservation &group) +{ + switch (group.packNum) + { + case 1: displayPack1(group); + break; + case 2: displayPack2(group); + break; + case 3: displayPack3(group); + break; + case 4: displayPack4(group); + break; + default: cout << "ERROR: Invalid package number.\n"; + } +} + +//************************************************************** +// Definition of function displayPack1. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 1. * +//************************************************************** + +void displayPack1(Reservation &group) +{ + cout << "Package: Devil's Courthouse Adventure Weekend\n"; + cout << "Number in party: " + << group.packs.climb.num << endl; + cout << "Base charges: $" + << group.packs.climb.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.climb.instruction << endl; + cout << "Equipment rental: $" + << group.packs.climb.equipment << endl; + cout << "Discount: $" + << group.packs.climb.discount << endl; + cout << "Total charges: $" + << group.packs.climb.charges << endl; + cout << "Required deposit: $" + << group.packs.climb.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack2. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 2. * +//************************************************************** + +void displayPack2(Reservation &group) +{ + cout << "Package: Scuba Bahama\n"; + cout << "Number in party: " + << group.packs.scuba.num << endl; + cout << "Base charges: $" + << group.packs.scuba.baseCharges << endl; + cout << "Instruction cost: $" + << group.packs.scuba.instruction << endl; + cout << "Discount: $" + << group.packs.scuba.discount << endl; + cout << "Total charges: $" + << group.packs.scuba.charges << endl; + cout << "Required deposit: $" + << group.packs.scuba.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack3. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 3. * +//************************************************************** + +void displayPack3(Reservation &group) +{ + cout << "Package: Sky Dive Colorado\n"; + cout << "Number in party: " + << group.packs.sky.num << endl; + cout << "Base charges: $" + << group.packs.sky.baseCharges << endl; + cout << "Lodging: $" + << group.packs.sky.lodging << endl; + cout << "Discount: $" + << group.packs.sky.discount << endl; + cout << "Total charges: $" + << group.packs.sky.charges << endl; + cout << "Required deposit: $" + << group.packs.sky.deposit << endl << endl; +} + +//************************************************************** +// Definition of function displayPack4. * +// Uses a Reservation reference parameter to hold the * +// vacation package information. This function displays the * +// information stored for vacation package 4. * +//************************************************************** + +void displayPack4(Reservation &group) +{ + cout << "Package: Barron Cliff Spelunk\n"; + cout << "Number in party: " + << group.packs.spel.num << endl; + cout << "Base charges: $" + << group.packs.spel.baseCharges << endl; + cout << "Equipment rental: $" + << group.packs.spel.equipment << endl; + cout << "Discount: $" + << group.packs.spel.discount << endl; + cout << "Total charges: $" + << group.packs.spel.charges << endl; + cout << "Required deposit: $" + << group.packs.spel.deposit << endl << endl; +} + +//************************************************************** +// Definition of function showRes. * +// Accepts an fstream object as an argument. Seeks the * +// beginning of the file and then reads and displays * +// each record. * +//************************************************************** + +void showRes(fstream &file) +{ + Reservation temp; + char skip[2]; + + file.seekg(0L, ios::beg); // Go to beginning of file. + file.read(reinterpret_cast(&temp), sizeof(temp)); + while (!file.eof()) + { + displayInfo(temp); + cout << "Type a character and press Enter " + << "to continue:"; + cin >> skip; + file.read(reinterpret_cast(&temp), sizeof(temp)); + } + if (file.fail()) + file.clear(); // Clear any error state +} \ No newline at end of file diff --git a/SourceCode/case studies/High Adventure Travel Agency - Part 3/resfile b/SourceCode/case studies/High Adventure Travel Agency - Part 3/resfile new file mode 100755 index 0000000..26283b5 Binary files /dev/null and b/SourceCode/case studies/High Adventure Travel Agency - Part 3/resfile differ diff --git a/SourceCode/case studies/Intersection of Sets/Program 7-32.cpp b/SourceCode/case studies/Intersection of Sets/Program 7-32.cpp new file mode 100755 index 0000000..ddd6c58 --- /dev/null +++ b/SourceCode/case studies/Intersection of Sets/Program 7-32.cpp @@ -0,0 +1,101 @@ +// This program allows the user to enter two sets of numbers. +// It finds the intersection of the two sets (which is the +// set of numbers contained in both sets). The intersecting +// values are displayed. +#include +using namespace std; + +// Function Prototypes +void getArrays(int [], int [], int); +int findIntersection(int [], int [], int [], int); +void displayIntValues(int [], int); + +int main() +{ + const int NUM_VALUES = 10; // Number of values in each array + int set1[NUM_VALUES], // First set + set2[NUM_VALUES], // Second set + intersection[NUM_VALUES], // Set containing intersection values + numIntValues; // number of values in intersection + + // Get values for the sets. + getArrays(set1, set2, NUM_VALUES); + + // Find the intersection of the two sets + numIntValues = findIntersection(set1, set2, + intersection, NUM_VALUES); + + // Display the intersecting values + displayIntValues(intersection, numIntValues); + return 0; +} + +//******************************************************** +// Definition of function getArrays * +// This function accepts two int arrays as arguments. * +// It prompts the user to enter 10 values for each array * +//******************************************************** + +void getArrays(int first[], int second[], int size) +{ + // Get values for first array. + cout << "Enter 10 values for the first set:\n"; + for (int index = 0; index < size; index++) + cin >> first[index]; + + // Get values for second array. + cout << "Enter 10 values for the second set:\n"; + for (int index = 0; index < size; index++) + cin >> second[index]; +} + + +//************************************************************ +// Definition of function findIntersection * +// This functon accepts three arrays as arguments. * +// The first two arrays (first and second) are scanned, * +// and all values appearing in both are stored in the * +// third array (intersect). The number of values that appear * +// in both arrays is returned. * +//************************************************************ + +int findIntersection(int first[], int second[], int intersect[], int size) +{ + int intCount = 0, // Number of intersecting values + index3 = 0; // Subscript variable for intersect array + + for (int index1 = 0; index1 < size; index1++) + { + for(int index2 = 0; index2 < size; index2++) + { + if (first[index1] == second[index2]) + { + intersect[index3] = first[index1]; + index3++; + intCount++; + } + } + } + return intCount; // Return the number of intersecting values. +} + +//******************************************************* +// Definition of function displayIntValues * +// This function acepts two arguments: an array of ints * +// and an int. The second argument is the number of * +// valid elements contained in the array. * +// These values are displayed, if there are any. * +//******************************************************* + +void displayIntValues(int intersect[], int num) +{ + if (!num) + cout << "There are no intersecting values.\n"; + else + { + cout << "Here is a list of the intersecting values:\n"; + for (int index = 0; index < num; index++) + cout << intersect[index] << " "; + cout << endl; + } +} \ No newline at end of file diff --git a/SourceCode/case studies/Loan Amortization/Program 5-27.cpp b/SourceCode/case studies/Loan Amortization/Program 5-27.cpp new file mode 100755 index 0000000..0dce3ac --- /dev/null +++ b/SourceCode/case studies/Loan Amortization/Program 5-27.cpp @@ -0,0 +1,69 @@ +// This program produces a loan amortization chart for the +// Central Mountain Credit Union. +#include +#include +#include // For pow function +using namespace std; + +int main() +{ + const int MONTHS = 12; // Months per year + double loan, // Loan amount + rate, // Annual interest rate + years, // Years of loan + balance, // Monthly balance + term, // Used to calculate payment + payment; // Monthly payment + + // Ask user for input. + cout << "Loan amount: $"; + cin >> loan; + cout << "Annual interest rate: "; + cin >> rate; + cout << "Years of loan: "; + cin >> years; + + // Calculate monthly payment. + term = pow((1 + rate / MONTHS), MONTHS * years); + payment = (loan * rate / MONTHS * term) / (term - 1.0); + + // Display monthly payment. + cout << fixed << showpoint << setprecision(2); + cout << "Monthly payment: $" << payment << endl; + + // Display report header. + cout << endl; + cout << setw(5) << "Month"; + cout << setw(10) << "Interest"; + cout << setw(10) << "Principal"; + cout << setw(10) << "Balance" << endl; + cout << "----------------------------------------\n"; + + // Produce a listing for each month. + balance = loan; + int numPayments = MONTHS * years; + for (int month = 1; month <= numPayments; month++) + { + double minterest, principal; + // Calculate monthly interest + minterest = rate / MONTHS * balance; + if (month != numPayments) + principal = payment - minterest; + + else // If this is the last month + { + principal = balance; + payment = balance + minterest; + } + + // Calculate the new loan balance. + balance -= principal; + + // Display payment figures + cout << setw(4) << month; + cout << setw(10) << minterest; + cout << setw(10) << principal; + cout << setw(10) << balance << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/Sales Commission/Program 4-31.cpp b/SourceCode/case studies/Sales Commission/Program 4-31.cpp new file mode 100755 index 0000000..89229d6 --- /dev/null +++ b/SourceCode/case studies/Sales Commission/Program 4-31.cpp @@ -0,0 +1,50 @@ +// This program is used by Crazy Al's Computer Emporium +// to calculate the monthly pay of commissioned sales people. +#include +#include +using namespace std; +int main() +{ + double sales, // Monthly Sales + rate, // Rate of Commission + commission, // Amount of Commission + advance, // Advanced Pay Drawn + pay; // Pay remaining to be paid + + // Ask user for the salesperson's sales and the + // amount of advanced pay. + cout << "Enter the salesperson's monthly sales: "; + cin >> sales; + cout << "Enter the amount of advanced pay for this "; + cout << "salesperson: "; + cin >> advance; + + // Determine the commission rate. + if (sales < 10000) + rate = 0.05; + else if (sales < 14999) + rate = 0.1; + else if (sales < 17999) + rate = 0.12; + else if (sales < 21999) + rate = 0.14; + else + rate = 0.16; + + // Calculate the sales commission. + commission = sales * rate; + + // Calculate the salesperson's pay. + pay = commission - advance; + + // Display the results. + cout << fixed << showpoint << setprecision(2); + cout << "\nPay Results\n"; + cout << "-----------\n"; + cout << "Sales: $" << sales << endl; + cout << "Commission Rate: " << rate << endl; + cout << "Commission: $" << commission << endl; + cout << "Advanced Pay: $" << advance << endl; + cout << "Remaining Pay: $" << pay << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/case studies/String Manipulation/Program 10-24.cpp b/SourceCode/case studies/String Manipulation/Program 10-24.cpp new file mode 100755 index 0000000..966ef3e --- /dev/null +++ b/SourceCode/case studies/String Manipulation/Program 10-24.cpp @@ -0,0 +1,195 @@ +// This program prints a simple form letter reminding a customer +// of an overdue account balance. +#include +#include +#include +using namespace std; + +// Function Prototypes +void printLetter(char *, char *, char *, char *, char *); +void getInfo(char *, char *, char *, char *, char *); +void getSal(char *); +void printline(const char *, int&); + +// Strings that make up the form letter +const char part1[] = "Dear "; +const char part2[] = "Our records show that your account has a" + " balance of $"; +const char part3[] = " and a past due amount of $"; +const char part4[] = "Your last payment was on "; +const char part5[] = "Since we haven't heard from you in some" + " time, would you please take a moment to send" + " us a check for the past-due amount? We value" + " your business and look forward to serving you" + " in the future.\n\n"; +const char part6[] = "Sincerely,\n"; +const char part7[] = "The Management\n\n"; +const char part8[] = "P.S. If you've already sent your payment, ignore" + " this reminder."; + +int main() +{ + char salutation[4]; // To hold the salutation + char lastName[16]; // Customer's last name + char lastPayment[16]; // Date of last payment + char balance[9]; // Account balace + char pastDue[9]; // Amount past due + char again; // To hold Y or N + + do + { + // Call getInfo to get input from the user + getInfo(salutation, lastName, balance, pastDue, + lastPayment); + cout << "\n\n"; + // Now print the form letter + printLetter(salutation, lastName, balance, pastDue, + lastPayment); + cout << "\n\nDo another letter? (Y/N) "; + cin >> again; + } while (toupper(again) == 'Y'); + return 0; +} + +//***************************************************************** +// Definition of function getInfo. * +// This function allows the user to enter the following items: * +// salutation, last name, account balance, past due amount, and * +// date of last payment. The function arguments are pointers to * +// strings where the input will be stored. * +//***************************************************************** + +void getInfo(char *sal, char *lname, char *bal, char *due, + char *lastPay) +{ + getSal(sal); + cout << "Last name: "; + cin >> lname; + lname[0] = toupper(lname[0]); + cout << "Account balance: "; + cin >> bal; + cout << "Past due Amount: "; + cin >> due; + cout << "Date of last payment (MM/DD/YYYY): "; + cin >> lastPay; +} + +//**************************************************************** +// Definition of function getSal. * +// This function gives the user a menu from which to pick a * +// suitable title for the letter's addressee. The choices are * +// Mr. and Ms. The choice will be copied to the address pointed * +// to by sal. * +//**************************************************************** + +void getSal(char *sal) +{ + int choice; + + do + { + cout << "salutation:\n"; + cout << "\t1) Mr.\n"; + cout << "\t2) Ms.\n"; + cout << "Select one: "; + cin >> choice; + } while (choice != 1 && choice != 2); + + if (choice == 1) + strcpy(sal, "Mr."); + else + strcpy(sal, "Ms."); +} + +//************************************************************* +// Definition of function printLetter. * +// This function prints the form letter. The parameters are * +// pointers to the fields that contain user input. * +//************************************************************* + +void printLetter(char *sal, char *lname, char *bal, char *due, + char *lastPay) +{ + int position; + + // Print the salutation part of the letter + position = 0; // Start a new line. + printline(part1, position); + cout << sal << " " << lname << ":" << endl << endl; + + // Print the body of the letter + position = 0; // Start a new line. + printline(part2, position); + cout << bal; // Print account balance. + + // Add length of balance to position. + position += strlen(bal); + printline(part3, position); + cout << due << ". "; // Print past due amount + position += strlen(due)+ 2; + + // Add length of due and the period and space at the + // end of the sentence to position. + printline(part4, position); + cout << lastPay << ". "; // Print date of last payment. + + // Now Add length of lastPay and the period and space at the + // end of the sentence to position. + position += strlen(lastPay) + 2; + printline(part5, position); + + // Print the closing. + position = 0; // Start a new line. + printline(part6, position); + position = 0; // Start a new line. + printline(part7, position); + + // Print the PS reminder. + position = 0; // Start a new line. + printline(part8, position); +} + +//******************************************************************* +// Definition of function printline. * +// This function has two parameters: line and startCount. * +// The string pointed to by line is printed. startCount is the * +// starting position of the line in an 80 character field. There * +// are 10-character left and right margins within the 80 * +// character field. The function performs word-wrap by looking * +// for space character within the line at or after the 60th * +// character. A new line is started when a space is found, or the * +// end of the field is reached. * +//******************************************************************* + +void printline(const char *line, int &startCount) +{ + int charCount = 0; + + if (startCount >= 70) // If the line is already at + { // or past the right margin... + cout << "\n"; // Start a new line. + startCount = 0; // Reset startCount. + } + + // The following while loop cycles through the string + // printing it one character at a time. It watches for + // spaces after the 60th position so word-wrap may be + // performed. + while (line[charCount] != '\0') + { + if (startCount >= 60 && line[charCount] == ' ') + { + cout << " \n"; // Print right margin. + charCount++; // Skip over the space. + startCount = 0; + } + if (startCount == 0) + { + cout << " "; // Print left margin. + startCount = 10; + } + cout.put(line[charCount]); // Print the character. + charCount++; // Update subscript. + startCount++; // Update position counter. + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Account.cpp b/SourceCode/chapter 13/Account.cpp new file mode 100755 index 0000000..1531464 --- /dev/null +++ b/SourceCode/chapter 13/Account.cpp @@ -0,0 +1,14 @@ +// Implementation file for the Account class. +#include "Account.h" + +bool Account::withdraw(double amount) +{ + if (balance < amount) + return false; // Not enough in the account + else + { + balance -= amount; + transactions++; + return true; + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Account.h b/SourceCode/chapter 13/Account.h new file mode 100755 index 0000000..86e8072 --- /dev/null +++ b/SourceCode/chapter 13/Account.h @@ -0,0 +1,42 @@ +// Specification file for the Account class. +#ifndef ACCOUNT_H +#define ACCOUNT_H + +class Account +{ +private: + double balance; // Account balance + double interestRate; // Interest rate for the period + double interest; // Interest earned for the period + int transactions; // Number of transactions +public: + Account(double iRate = 0.045, double bal = 0) + { balance = bal; + interestRate = iRate; + interest = 0; + transactions = 0; } + + void setInterestRate(double iRate) + { interestRate = iRate; } + + void makeDeposit(double amount) + { balance += amount; transactions++; } + + bool withdraw(double amount); // Defined in Account.cpp + + void calcInterest() + { interest = balance * interestRate; balance += interest; } + + double getInterestRate() const + { return interestRate; } + + double getBalance() const + { return balance; } + + double getInterest() const + { return interest; } + + int getTransactions() const + { return transactions; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/ContactInfo Version 1/ContactInfo.h b/SourceCode/chapter 13/ContactInfo Version 1/ContactInfo.h new file mode 100755 index 0000000..aa08154 --- /dev/null +++ b/SourceCode/chapter 13/ContactInfo Version 1/ContactInfo.h @@ -0,0 +1,34 @@ +// Specification file for the Contact class. +#ifndef CONTACTINFO_H +#define CONTACTINFO_H +#include // Needed for strlen and strcpy + +// ContactInfo class declaration. +class ContactInfo +{ +private: + char *name; // The contact's name + char *phone; // The contact's phone number +public: + // Constructor + ContactInfo(char *n, char *p) + { // Allocate just enough memory for the name and phone number. + name = new char[strlen(n) + 1]; + phone = new char[strlen(p) + 1]; + + // Copy the name and phone number to the allocated memory. + strcpy(name, n); + strcpy(phone, p); } + + // Destructor + ~ContactInfo() + { delete [] name; + delete [] phone; } + + const char *getName() const + { return name; } + + const char *getPhoneNumber() const + { return phone; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/ContactInfo Version 1/Pr13-12.cpp b/SourceCode/chapter 13/ContactInfo Version 1/Pr13-12.cpp new file mode 100755 index 0000000..1a3c4d8 --- /dev/null +++ b/SourceCode/chapter 13/ContactInfo Version 1/Pr13-12.cpp @@ -0,0 +1,16 @@ +// This program demonstrates a class with a destructor. +#include +#include "ContactInfo.h" +using namespace std; + +int main() +{ + // Define a ContactInfo object with the following data: + // Name: Kristen Lee Phone Number: 555-2021 + ContactInfo entry("Kristen Lee", "555-2021"); + + // Display the object's data. + cout << "Name: " << entry.getName() << endl; + cout << "Phone Number: " << entry.getPhoneNumber() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/ContactInfo Version 2/ContactInfo.h b/SourceCode/chapter 13/ContactInfo Version 2/ContactInfo.h new file mode 100755 index 0000000..580993b --- /dev/null +++ b/SourceCode/chapter 13/ContactInfo Version 2/ContactInfo.h @@ -0,0 +1,44 @@ +// Contact class specification file (version 2) +#ifndef CONTACTINFO_H +#define CONTACTINFO_H +#include // Needed for strlen and strcpy + +// ContactInfo class declaration. +class ContactInfo +{ +private: + char *name; // The contact's name + char *phone; // The contact's phone number + + // Private member function: initName + // This function initializes the name attribute. + void initName(char *n) + { name = new char[strlen(n) + 1]; + strcpy(name, n); } + + // Private member function: initPhone + // This function initializes the phone attribute. + void initPhone(char *p) + { phone = new char[strlen(p) + 1]; + strcpy(phone, p); } +public: + // Constructor + ContactInfo(char *n, char *p) + { // Initialize the name attribute. + initName(n); + + // Initialize the phone attribute. + initPhone(n); } + + // Destructor + ~ContactInfo() + { delete [] name; + delete [] phone; } + + const char *getName() const + { return name; } + + const char *getPhoneNumber() const + { return phone; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Dice/Die.cpp b/SourceCode/chapter 13/Dice/Die.cpp new file mode 100755 index 0000000..be47af9 --- /dev/null +++ b/SourceCode/chapter 13/Dice/Die.cpp @@ -0,0 +1,55 @@ +// Implememtation file for the Die class +#include // For rand and srand +#include // For the time function +#include "Die.h" +using namespace std; + +//******************************************************* +// The constructor accepts an argument for the number * +// of sides for the die, and performs a roll. * +//******************************************************* +Die::Die(int numSides) +{ + // Get the system time. + unsigned seed = time(0); + + // Seed the random number generator. + srand(seed); + + // Set the number of sides. + sides = numSides; + + // Perform an initial roll. + roll(); +} + +//******************************************************* +// The roll member function simulates the rolling of * +// the die. * +//******************************************************* +void Die::roll() +{ + // Constant for the minimum die value + const int MIN_VALUE = 1; // Minimum die value + + // Get a random value for the die. + value = (rand() % (sides - MIN_VALUE + 1)) + MIN_VALUE; +} + +//******************************************************* +// The getSides member function returns the number of * +// for this die. * +//******************************************************* +int Die::getSides() +{ + return sides; +} + +//******************************************************* +// The getValue member function returns the die's value.* +//******************************************************* +int Die::getValue() +{ + return value; +} + diff --git a/SourceCode/chapter 13/Dice/Die.h b/SourceCode/chapter 13/Dice/Die.h new file mode 100755 index 0000000..585babc --- /dev/null +++ b/SourceCode/chapter 13/Dice/Die.h @@ -0,0 +1,17 @@ +// Specification file for the Die class +#ifndef DIE_H +#define DIE_H + +class Die +{ +private: + int sides; // Number of sides + int value; // The die's value + +public: + Die(int); // Constructor + void roll(); // Rolls the die + int getSides(); // Returns the number of sides + int getValue(); // REturns the die's value +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Dice/Pr13-16.cpp b/SourceCode/chapter 13/Dice/Pr13-16.cpp new file mode 100755 index 0000000..38d807a --- /dev/null +++ b/SourceCode/chapter 13/Dice/Pr13-16.cpp @@ -0,0 +1,39 @@ +// This program simulates the rolling of dice. +#include +#include "Die.h" +using namespace std; + +int main() +{ + const int DIE1_SIDES = 6; // Number of sides for die #1 + const int DIE2_SIDES = 12; // Number of sides for die #2 + const int MAX_ROLLS = 5; // Number of times to roll + + // Create two instances of the Die class. + Die die1(DIE1_SIDES); + Die die2(DIE2_SIDES); + + // Display the initial state of the dice. + cout << "This simulates the rolling of a " + << die1.getSides() << " sided die and a " + << die2.getSides() << " sided die.\n"; + + cout << "Initial value of the dice:\n"; + cout << die1.getValue() << " " + << die2.getValue() << endl; + + // Roll the dice five times. + cout << "Rolling the dice " << MAX_ROLLS + << " times.\n"; + for (int count = 0; count < MAX_ROLLS; count++) + { + // Roll the dice. + die1.roll(); + die2.roll(); + + // Display the values of the dice. + cout << die1.getValue() << " " + << die2.getValue() << endl; + } + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/IntegerList.cpp b/SourceCode/chapter 13/IntegerList.cpp new file mode 100755 index 0000000..7f04738 --- /dev/null +++ b/SourceCode/chapter 13/IntegerList.cpp @@ -0,0 +1,77 @@ +// Implementation file for the IntegerList class. +#include +#include +#include "IntegerList.h" +using namespace std; + +//*********************************************************** +// The constructor sets each element to zero. * +//*********************************************************** + +IntegerList::IntegerList(int size) +{ + list = new int[size]; + numElements = size; + for (int ndx = 0; ndx < size; ndx++) + list[ndx] = 0; +} + +//*********************************************************** +// The destructor releases allocated memory. * +//*********************************************************** + +IntegerList::~IntegerList() +{ + delete [] list; +} + +//*********************************************************** +// isValid member function. * +// This private member functon returns true if the argument * +// is a valid subscript, or false otherwise. * +//*********************************************************** + +bool IntegerList::isValid(int element) const +{ + bool status; + + if (element < 0 || element >= numElements) + status = false; + else + status = true; + return status; +} + +//*********************************************************** +// setElement member function. * +// Stores a value in a specific element of the list. If an * +// invalid subscript is passed, the program aborts. * +//*********************************************************** + +void IntegerList::setElement(int element, int value) +{ + if (isValid(element)) + list[element] = value; + else + { + cout << "Error: Invalid subscript\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// getElement member function. * +// Returns the value stored at the specified element. * +// If an invalid subscript is passed, the program aborts. * +//*********************************************************** + +int IntegerList::getElement(int element) const +{ + if (isValid(element)) + return list[element]; + else + { + cout << "Error: Invalid subscript\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/IntegerList.h b/SourceCode/chapter 13/IntegerList.h new file mode 100755 index 0000000..d870a8b --- /dev/null +++ b/SourceCode/chapter 13/IntegerList.h @@ -0,0 +1,17 @@ +// Specification file for the the IntegerList class. +#ifndef INTEGERLIST_H +#define INTEGERLIST_H + +class IntegerList +{ +private: + int *list; // Pointer to the array. + int numElements; // Number of elements. + bool isValid(int) const; // Validates subscripts. +public: + IntegerList(int); // Constructor + ~IntegerList(); // Destructor + void setElement(int, int); // Sets an element to a value + int getElement(int) const; // Returns an element +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/InventoryItem/InventoryItem.h b/SourceCode/chapter 13/InventoryItem/InventoryItem.h new file mode 100755 index 0000000..1b7aa2b --- /dev/null +++ b/SourceCode/chapter 13/InventoryItem/InventoryItem.h @@ -0,0 +1,57 @@ +// This class has overloaded constructors. +#ifndef INVENTORYITEM_H +#define INVENTORYITEM_H +#include +using namespace std; + +class InventoryItem +{ +private: + string description; // The item description + double cost; // The item cost + int units; // Number of units on hand +public: + // Constructor #1 + InventoryItem() + { // Initialize description, cost, and units. + description = ""; + cost = 0.0; + units = 0; } + + // Constructor #2 + InventoryItem(string desc) + { // Assign the value to description. + description = desc; + + // Initialize cost and units. + cost = 0.0; + units = 0; } + + // Constructor #3 + InventoryItem(string desc, double c, int u) + { // Assign values to description, cost, and units. + description = desc; + cost = c; + units = u; } + + // Mutator functions + void setDescription(string d) + { description = d; } + + void setCost(double c) + { cost = c; } + + void setUnits(int u) + { units = u; } + + // Accessor functions + string getDescription() const + { return description; } + + double getCost() const + { return cost; } + + int getUnits() const + { return units; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/InventoryItem/Pr13-13.cpp b/SourceCode/chapter 13/InventoryItem/Pr13-13.cpp new file mode 100755 index 0000000..6f1fadb --- /dev/null +++ b/SourceCode/chapter 13/InventoryItem/Pr13-13.cpp @@ -0,0 +1,41 @@ +// This program demonstrates a class with overloaded constructors. +#include +#include +#include "InventoryItem.h" + +int main() +{ + // Create an InventoryItem object and call + // the default constructor. + InventoryItem item1; + item1.setDescription("Hammer"); // Set the description + item1.setCost(6.95); // Set the cost + item1.setUnits(12); // Set the units + + // Create an InventoryItem object and call + // constructor #2. + InventoryItem item2("Pliers"); + + // Create an InventoryItem object and call + // constructor #3. + InventoryItem item3("Wrench", 8.75, 20); + + cout << "The following items are in inventory:\n"; + cout << setprecision(2) << fixed << showpoint; + + // Display the data for item 1. + cout << "Description: " << item1.getDescription() << endl; + cout << "Cost: $" << item1.getCost() << endl; + cout << "Units on Hand: " << item1.getUnits() << endl << endl; + + // Display the data for item 2. + cout << "Description: " << item2.getDescription() << endl; + cout << "Cost: $" << item2.getCost() << endl; + cout << "Units on Hand: " << item2.getUnits() << endl << endl; + + // Display the data for item 3. + cout << "Description: " << item3.getDescription() << endl; + cout << "Cost: $" << item3.getCost() << endl; + cout << "Units on Hand: " << item3.getUnits() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/InventoryItem/Pr13-14.cpp b/SourceCode/chapter 13/InventoryItem/Pr13-14.cpp new file mode 100755 index 0000000..4237e03 --- /dev/null +++ b/SourceCode/chapter 13/InventoryItem/Pr13-14.cpp @@ -0,0 +1,30 @@ +// This program demonstrates an array of class object. +#include +#include +#include "InventoryItem.h" +using namespace std; + +int main() +{ + const int NUM_ITEMS = 5; + InventoryItem inventory[NUM_ITEMS] = { + InventoryItem("Hammer", 6.95, 12), + InventoryItem("Wrench", 8.75, 20), + InventoryItem("Pliers", 3.75, 10), + InventoryItem("Ratchet", 7.95, 14), + InventoryItem("Screwdriver", 2.50, 22) }; + + cout << setw(14) << "Inventory Item" + << setw(8) << "Cost" << setw(8) + << setw(16) << "Units on Hand\n"; + cout << "-------------------------------------\n"; + + for (int i = 0; i < NUM_ITEMS; i++) + { + cout << setw(14) << inventory[i].getDescription(); + cout << setw(8) << inventory[i].getCost(); + cout << setw(7) << inventory[i].getUnits() << endl; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-1.cpp b/SourceCode/chapter 13/Pr13-1.cpp new file mode 100755 index 0000000..487e3e7 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-1.cpp @@ -0,0 +1,92 @@ +// This program demonstrates a simple class. +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + double rectWidth; // Local variable for width + double rectLength; // Local variable for length + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + // Store the width and length of the rectangle + // in the box object. + box.setWidth(rectWidth); + box.setLength(rectLength); + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-11.cpp b/SourceCode/chapter 13/Pr13-11.cpp new file mode 100755 index 0000000..d4484c0 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-11.cpp @@ -0,0 +1,33 @@ +// This program demonstrates a destructor. +#include +using namespace std; + +class Demo +{ +public: + Demo(); // Constructor + ~Demo(); // Destructor +}; + +Demo::Demo() +{ + cout << "Welcome to the constructor!\n"; +} + +Demo::~Demo() +{ + cout << "The destructor is now running.\n"; +} + +//********************************************* +// Function main. * +//********************************************* + +int main() +{ + Demo demoObject; // Define a demo object; + + cout << "This program demonstrates an object\n"; + cout << "with a constructor and destructor.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-15.cpp b/SourceCode/chapter 13/Pr13-15.cpp new file mode 100755 index 0000000..5dc20de --- /dev/null +++ b/SourceCode/chapter 13/Pr13-15.cpp @@ -0,0 +1,116 @@ +// This program demonstrates the Account class. +#include +#include +#include +#include "Account.h" +using namespace std; + +// Function prototypes +void displayMenu(); +void makeDeposit(Account &); +void withdraw(Account &); + +int main() +{ + Account savings; // Savings account object + char choice; // Menu selection + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + do + { + // Display the menu and get a valid selection. + displayMenu(); + cin >> choice; + while (toupper(choice) < 'A' || toupper(choice) > 'G') + { + cout << "Please make a choice in the range " + << "of A through G:"; + cin >> choice; + } + + // Process the user's menu selection. + switch(choice) + { + case 'a': + case 'A': cout << "The current balance is $"; + cout << savings.getBalance() << endl; + break; + case 'b': + case 'B': cout << "There have been "; + cout << savings.getTransactions() + << " transactions.\n"; + break; + case 'c': + case 'C': cout << "Interest earned for this period: $"; + cout << savings.getInterest() << endl; + break; + case 'd': + case 'D': makeDeposit(savings); + break; + case 'e': + case 'E': withdraw(savings); + break; + case 'f': + case 'F': savings.calcInterest(); + cout << "Interest added.\n"; + } + } while (toupper(choice) != 'G'); + + return 0; +} + +//**************************************************** +// Definition of function displayMenu. This function * +// displays the user's menu on the screen. * +//**************************************************** + +void displayMenu() +{ + cout << "\n MENU\n"; + cout << "-----------------------------------------\n"; + cout << "A) Display the account balance\n"; + cout << "B) Display the number of transactions\n"; + cout << "C) Display interest earned for this period\n"; + cout << "D) Make a deposit\n"; + cout << "E) Make a withdrawal\n"; + cout << "F) Add interest for this period\n"; + cout << "G) Exit the program\n\n"; + cout << "Enter your choice: "; +} + +//************************************************************* +// Definition of function makeDeposit. This function accepts * +// a reference to an Account object. The user is prompted for * +// the dollar amount of the deposit, and the makeDeposit * +// member of the Account object is then called. * +//************************************************************* + +void makeDeposit(Account &acnt) +{ + double dollars; + + cout << "Enter the amount of the deposit: "; + cin >> dollars; + cin.ignore(); + acnt.makeDeposit(dollars); +} + +//************************************************************* +// Definition of function withdraw. This function accepts * +// a reference to an Account object. The user is prompted for * +// the dollar amount of the withdrawal, and the withdraw * +// member of the Account object is then called. * +//************************************************************* + +void withdraw(Account &acnt) +{ + double dollars; + + cout << "Enter the amount of the withdrawal: "; + cin >> dollars; + cin.ignore(); + if (!acnt.withdraw(dollars)) + cout << "ERROR: Withdrawal amount too large.\n\n"; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-17.cpp b/SourceCode/chapter 13/Pr13-17.cpp new file mode 100755 index 0000000..c5a3d23 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-17.cpp @@ -0,0 +1,35 @@ +// This program demonstrates the IntegerList class. +#include +#include "IntegerList.h" +using namespace std; + +int main() +{ + const int SIZE = 20; + IntegerList numbers(SIZE); + int val, x; + + // Store 9s in the list and display an asterisk + // each time a 9 is successfully stored. + for (x = 0; x < SIZE; x++) + { + numbers.setElement(x, 9); + cout << "* "; + } + cout << endl; + + // Display the 9s. + for (x = 0; x < SIZE; x++) + { + val = numbers.getElement(x); + cout << val << " "; + } + cout << endl; + + // Attempt to store a value outside the list's bounds. + numbers.setElement(50, 9); + + // Will this message display? + cout << "Element 50 successfully set.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-2.cpp b/SourceCode/chapter 13/Pr13-2.cpp new file mode 100755 index 0000000..27abe45 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-2.cpp @@ -0,0 +1,109 @@ +// This program creates three instances of the Rectangle class. +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + double number; // To hold a number + double totalArea; // The total area + Rectangle kitchen; // To hold kitchen dimensions + Rectangle bedroom; // To hold bedroom dimensions + Rectangle den; // To hold den dimensions + + // Get the kitchen dimensions. + cout << "What is the kitchen's length? "; + cin >> number; // Get the length + kitchen.setLength(number); // Store in kitchen object + cout << "What is the kitchen's width? "; + cin >> number; // Get the width + kitchen.setWidth(number); // Store in kitchen object + + // Get the bedroom dimensions. + cout << "What is the bedroom's length? "; + cin >> number; // Get the length + bedroom.setLength(number); // Store in bedroom object + cout << "What is the bedroom's width? "; + cin >> number; // Get the width + bedroom.setWidth(number); // Store in bedroom object + + // Get the den dimensions. + cout << "What is the den's length? "; + cin >> number; // Get the length + den.setLength(number); // Store in den object + cout << "What is the den's width? "; + cin >> number; // Get the width + den.setWidth(number); // Store in den object + + // Calculate the total area of the three rooms. + totalArea = kitchen.getArea() + bedroom.getArea() + + den.getArea(); + + // Display the total area of the three rooms. + cout << "The total area of the three rooms is " + << totalArea << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-3.cpp b/SourceCode/chapter 13/Pr13-3.cpp new file mode 100755 index 0000000..9b0cb51 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-3.cpp @@ -0,0 +1,122 @@ +// This program creates three instances of the Rectangle class. +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + double number; // To hold a number + double totalArea; // The total area + Rectangle *kitchen = nullptr; // To point to kitchen dimensions + Rectangle *bedroom = nullptr; // To point to bedroom dimensions + Rectangle *den = nullptr; // To point to den dimensions + + // Dynamically allocate the objects. + kitchen = new Rectangle; + bedroom = new Rectangle; + den = new Rectangle; + + // Get the kitchen dimensions. + cout << "What is the kitchen's length? "; + cin >> number; // Get the length + kitchen->setLength(number); // Store in kitchen object + cout << "What is the kitchen's width? "; + cin >> number; // Get the width + kitchen->setWidth(number); // Store in kitchen object + + // Get the bedroom dimensions. + cout << "What is the bedroom's length? "; + cin >> number; // Get the length + bedroom->setLength(number); // Store in bedroom object + cout << "What is the bedroom's width? "; + cin >> number; // Get the width + bedroom->setWidth(number); // Store in bedroom object + + // Get the den dimensions. + cout << "What is the den's length? "; + cin >> number; // Get the length + den->setLength(number); // Store in den object + cout << "What is the den's width? "; + cin >> number; // Get the width + den->setWidth(number); // Store in den object + + // Calculate the total area of the three rooms. + totalArea = kitchen->getArea() + bedroom->getArea() + + den->getArea(); + + // Display the total area of the three rooms. + cout << "The total area of the three rooms is " + << totalArea << endl; + + // Delete the objects from memory. + delete kitchen; + delete bedroom; + delete den; + kitchen = nullptr; // Make kitchen a null pointer. + bedroom = nullptr; // Make bedroom a null pointer. + den = nullptr; // Make den a null pointer. + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-4.cpp b/SourceCode/chapter 13/Pr13-4.cpp new file mode 100755 index 0000000..47a553b --- /dev/null +++ b/SourceCode/chapter 13/Pr13-4.cpp @@ -0,0 +1,113 @@ +// This program uses smart pointers to allocate three +// instances of the Rectangle class. +#include +#include +using namespace std; + +// Rectangle class declaration. +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +//************************************************** +// setWidth assigns a value to the width member. * +//************************************************** + +void Rectangle::setWidth(double w) +{ + width = w; +} + +//************************************************** +// setLength assigns a value to the length member. * +//************************************************** + +void Rectangle::setLength(double len) +{ + length = len; +} + +//************************************************** +// getWidth returns the value in the width member. * +//************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//**************************************************** +// getLength returns the value in the length member. * +//**************************************************** + +double Rectangle::getLength() const +{ + return length; +} + +//***************************************************** +// getArea returns the product of width times length. * +//***************************************************** + +double Rectangle::getArea() const +{ + return width * length; +} + +//***************************************************** +// Function main * +//***************************************************** + +int main() +{ + double number; // To hold a number + double totalArea; // The total area + + // Dynamically allocate the objects. + unique_ptr kitchen(new Rectangle); + unique_ptr bedroom(new Rectangle); + unique_ptr den(new Rectangle); + + // Get the kitchen dimensions. + cout << "What is the kitchen's length? "; + cin >> number; // Get the length + kitchen->setLength(number); // Store in kitchen object + cout << "What is the kitchen's width? "; + cin >> number; // Get the width + kitchen->setWidth(number); // Store in kitchen object + + // Get the bedroom dimensions. + cout << "What is the bedroom's length? "; + cin >> number; // Get the length + bedroom->setLength(number); // Store in bedroom object + cout << "What is the bedroom's width? "; + cin >> number; // Get the width + bedroom->setWidth(number); // Store in bedroom object + + // Get the den dimensions. + cout << "What is the den's length? "; + cin >> number; // Get the length + den->setLength(number); // Store in den object + cout << "What is the den's width? "; + cin >> number; // Get the width + den->setWidth(number); // Store in den object + + // Calculate the total area of the three rooms. + totalArea = kitchen->getArea() + bedroom->getArea() + + den->getArea(); + + // Display the total area of the three rooms. + cout << "The total area of the three rooms is " + << totalArea << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Pr13-6.cpp b/SourceCode/chapter 13/Pr13-6.cpp new file mode 100755 index 0000000..abf3f63 --- /dev/null +++ b/SourceCode/chapter 13/Pr13-6.cpp @@ -0,0 +1,29 @@ +// This program demonstrates a constructor. +#include +using namespace std; + +// Demo class declaration. + +class Demo +{ +public: + Demo(); // Constructor +}; + +Demo::Demo() +{ + cout << "Welcome to the constructor!\n"; +} + +//***************************************** +// Function main. * +//***************************************** + +int main() +{ + Demo demoObject; // Define a Demo object; + + cout << "This program demonstrates an object\n"; + cout << "with a constructor.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 1/Pr13-5.cpp b/SourceCode/chapter 13/Rectangle Version 1/Pr13-5.cpp new file mode 100755 index 0000000..ea45d2f --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 1/Pr13-5.cpp @@ -0,0 +1,33 @@ +// This program uses the Rectangle class, which is declared in +// the Rectangle.h file. The member Rectangle class's member +// functions are defined in the Rectangle.cpp file. This program +// should be compiled with those files in a project. +#include +#include "Rectangle.h" // Needed for Rectangle class +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + double rectWidth; // Local variable for width + double rectLength; // Local variable for length + + // Get the rectangle's width and length from the user. + cout << "This program will calculate the area of a\n"; + cout << "rectangle. What is the width? "; + cin >> rectWidth; + cout << "What is the length? "; + cin >> rectLength; + + // Store the width and length of the rectangle + // in the box object. + box.setWidth(rectWidth); + box.setLength(rectLength); + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 1/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.cpp new file mode 100755 index 0000000..784c834 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.cpp @@ -0,0 +1,62 @@ +// Implementation file for the Rectangle class. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// getWidth returns the value in the member variable width. * +//*********************************************************** + +double Rectangle::getWidth() const +{ + return width; +} + +//************************************************************* +// getLength returns the value in the member variable length. * +//************************************************************* + +double Rectangle::getLength() const +{ + return length; +} + +//************************************************************ +// getArea returns the product of width times length. * +//************************************************************ + +double Rectangle::getArea() const +{ + return width * length; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 1/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.h new file mode 100755 index 0000000..1cbef04 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 1/Rectangle.h @@ -0,0 +1,20 @@ +// Specification file for the Rectangle class. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +// Rectangle class declaration. + +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + double getWidth() const; + double getLength() const; + double getArea() const; +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 2/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.cpp new file mode 100755 index 0000000..6038ae4 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.cpp @@ -0,0 +1,37 @@ +// Implementation file for the Rectangle class. +// In this version of the class, the getWidth, getLength, +// and getArea functions are written inline in Rectangle.h. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 2/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.h new file mode 100755 index 0000000..9630ae8 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 2/Rectangle.h @@ -0,0 +1,24 @@ +// Specification file for the Rectangle class +// This version uses some inline member functions. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 3/Pr13-7.cpp b/SourceCode/chapter 13/Rectangle Version 3/Pr13-7.cpp new file mode 100755 index 0000000..f775ee5 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 3/Pr13-7.cpp @@ -0,0 +1,16 @@ +// This program uses the Rectangle class's constructor. +#include +#include "Rectangle.h" // Needed for Rectangle class +using namespace std; + +int main() +{ + Rectangle box; // Define an instance of the Rectangle class + + // Display the rectangle's data. + cout << "Here is the rectangle's data:\n"; + cout << "Width: " << box.getWidth() << endl; + cout << "Length: " << box.getLength() << endl; + cout << "Area: " << box.getArea() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 3/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.cpp new file mode 100755 index 0000000..d090c67 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.cpp @@ -0,0 +1,46 @@ +// Implementation file for the Rectangle class. +// This version has a constructor. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// The constructor initializes width and length to 0.0. * +//*********************************************************** + +Rectangle::Rectangle() +{ + width = 0.0; + length = 0.0; +} + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 3/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.h new file mode 100755 index 0000000..b40f846 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 3/Rectangle.h @@ -0,0 +1,25 @@ +// Specification file for the Rectangle class +// This version has a constructor. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + Rectangle(); // Constructor + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 4/Pr13-8.cpp b/SourceCode/chapter 13/Rectangle Version 4/Pr13-8.cpp new file mode 100755 index 0000000..647eb35 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 4/Pr13-8.cpp @@ -0,0 +1,32 @@ +// This program calls the Rectangle class constructor. +#include +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + double houseWidth, // To hold the room width + houseLength; // To hold the room length + + // Get the width of the house. + cout << "In feet, how wide is your house? "; + cin >> houseWidth; + + // Get the length of the house. + cout << "In feet, how long is your house? "; + cin >> houseLength; + + // Create a Rectangle object. + Rectangle house(houseWidth, houseLength ); + + // Display the house's width, length, and area. + cout << setprecision(2) << fixed; + cout << "The house is " << house.getWidth() + << " feet wide.\n"; + cout << "The house is " << house.getLength() + << " feet long.\n"; + cout << "The house has " << house.getArea() + << " square feet of area.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 4/Rectangle.cpp b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.cpp new file mode 100755 index 0000000..200f8fb --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.cpp @@ -0,0 +1,46 @@ +// Implementation file for the Rectangle class. +// This version has a constructor that accepts arguments. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// The constructor accepts arguments for width and length. * +//*********************************************************** + +Rectangle::Rectangle(double w, double len) +{ + width = w; + length = len; +} + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Rectangle Version 4/Rectangle.h b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.h new file mode 100755 index 0000000..ac8f474 --- /dev/null +++ b/SourceCode/chapter 13/Rectangle Version 4/Rectangle.h @@ -0,0 +1,25 @@ +// Specification file for the Rectangle class +// This version has a constructor. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + Rectangle(double, double); // Constructor + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 1/Pr13-9.cpp b/SourceCode/chapter 13/Sale Version 1/Pr13-9.cpp new file mode 100755 index 0000000..0689cdd --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 1/Pr13-9.cpp @@ -0,0 +1,28 @@ +// This program demonstrates passing an argument to a constructor. +#include +#include +#include "Sale.h" +using namespace std; + +int main() +{ + const double TAX_RATE = 0.06; // 6 percent sales tax rate + double cost; // To hold the item cost + + // Get the cost of the item. + cout << "Enter the cost of the item: "; + cin >> cost; + + // Create a Sale object for this transaction. + Sale itemSale(cost, TAX_RATE); + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the sales tax and total. + cout << "The amount of sales tax is $" + << itemSale.getTax() << endl; + cout << "The total of the sale is $"; + cout << itemSale.getTotal() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 1/Sale.h b/SourceCode/chapter 13/Sale Version 1/Sale.h new file mode 100755 index 0000000..77b528b --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 1/Sale.h @@ -0,0 +1,27 @@ +// Specification file for the Sale class. +#ifndef SALE_H +#define SALE_H + +class Sale +{ +private: + double itemCost; // Cost of the item + double taxRate; // Sales tax rate +public: + Sale(double cost, double rate) + { itemCost = cost; + taxRate = rate; } + + double getItemCost() const + { return itemCost; } + + double getTaxRate() const + { return taxRate; } + + double getTax() const + { return (itemCost * taxRate); } + + double getTotal() const + { return (itemCost + getTax()); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 2/Pr13-10.cpp b/SourceCode/chapter 13/Sale Version 2/Pr13-10.cpp new file mode 100755 index 0000000..ffda451 --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 2/Pr13-10.cpp @@ -0,0 +1,29 @@ +// This program uses a constructor's default argument. +#include +#include +#include "Sale.h" +using namespace std; + +int main() +{ + double cost; // To hold the item cost + + // Get the cost of the item. + cout << "Enter the cost of the item: "; + cin >> cost; + + // Create a Sale object for this transaction. + // Specify the item cost, but use the default + // tax rate of 5 percent. + Sale itemSale(cost); + + // Set numeric output formatting. + cout << fixed << showpoint << setprecision(2); + + // Display the sales tax and total. + cout << "The amount of sales tax is $" + << itemSale.getTax() << endl; + cout << "The total of the sale is $"; + cout << itemSale.getTotal() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 13/Sale Version 2/Sale.h b/SourceCode/chapter 13/Sale Version 2/Sale.h new file mode 100755 index 0000000..8cffa06 --- /dev/null +++ b/SourceCode/chapter 13/Sale Version 2/Sale.h @@ -0,0 +1,28 @@ +// This version of the Sale class uses a default argument +// in the constructor. +#ifndef SALE_H +#define SALE_H + +class Sale +{ +private: + double itemCost; // Cost of the item + double taxRate; // Sales tax rate +public: + Sale(double cost, double rate = 0.05) + { itemCost = cost; + taxRate = rate; } + + double getItemCost() const + { return itemCost; } + + double getTaxRate() const + { return taxRate; } + + double getTax() const + { return (itemCost * taxRate); } + + double getTotal() const + { return (itemCost + getTax()); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 1/Budget.h b/SourceCode/chapter 14/Budget Version 1/Budget.h new file mode 100755 index 0000000..ef246cf --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 1/Budget.h @@ -0,0 +1,28 @@ +#ifndef BUDGET_H +#define BUDGET_H + +// Budget class declaration +class Budget +{ +private: + static double corpBudget; // Static member + double divisionBudget; // Instance member +public: + Budget() + { divisionBudget = 0; } + + void addBudget(double b) + { divisionBudget += b; + corpBudget += b; } + + double getDivisionBudget() const + { return divisionBudget; } + + double getCorpBudget() const + { return corpBudget; } +}; + +// Definition of static member variable corpBudget +double Budget::corpBudget = 0; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 1/Pr14-2.cpp b/SourceCode/chapter 14/Budget Version 1/Pr14-2.cpp new file mode 100755 index 0000000..5ead76e --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 1/Pr14-2.cpp @@ -0,0 +1,35 @@ +// This program demonstrates a static class member variable. +#include +#include +#include "Budget.h" +using namespace std; + +int main() +{ + int count; // Loop counter + const int NUM_DIVISIONS = 4; // Number of divisions + Budget divisions[NUM_DIVISIONS]; // Array of Budget objects + + // Get the budget requests for each division. + for (count = 0; count < NUM_DIVISIONS; count++) + { + double budgetAmount; + cout << "Enter the budget request for division "; + cout << (count + 1) << ": "; + cin >> budgetAmount; + divisions[count].addBudget(budgetAmount); + } + + // Display the budget requests and the corporate budget. + cout << fixed << showpoint << setprecision(2); + cout << "\nHere are the division budget requests:\n"; + for (count = 0; count < NUM_DIVISIONS; count++) + { + cout << "\tDivision " << (count + 1) << "\t$ "; + cout << divisions[count].getDivisionBudget() << endl; + } + cout << "\tTotal Budget Requests:\t$ "; + cout << divisions[0].getCorpBudget() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 2/Budget.cpp b/SourceCode/chapter 14/Budget Version 2/Budget.cpp new file mode 100755 index 0000000..3278b48 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 2/Budget.cpp @@ -0,0 +1,15 @@ +#include "Budget.h" + +// Definition of corpBudget static member variable +double Budget::corpBudget = 0; + +//********************************************************** +// Definition of static member function mainOffice. * +// This function adds the main office's budget request to * +// the corpBudget variable. * +//********************************************************** + +void Budget::mainOffice(double moffice) +{ + corpBudget += moffice; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 2/Budget.h b/SourceCode/chapter 14/Budget Version 2/Budget.h new file mode 100755 index 0000000..9ea96b8 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 2/Budget.h @@ -0,0 +1,27 @@ +#ifndef BUDGET_H +#define BUDGET_H + +// Budget class declaration +class Budget +{ +private: + static double corpBudget; // Static member variable + double divisionBudget; // Instance member variable +public: + Budget() + { divisionBudget = 0; } + + void addBudget(double b) + { divisionBudget += b; + corpBudget += b; } + + double getDivisionBudget() const + { return divisionBudget; } + + double getCorpBudget() const + { return corpBudget; } + + static void mainOffice(double); // Static member function +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 2/Pr14-3.cpp b/SourceCode/chapter 14/Budget Version 2/Pr14-3.cpp new file mode 100755 index 0000000..d77028c --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 2/Pr14-3.cpp @@ -0,0 +1,43 @@ +// This program demonstrates a static member function. +#include +#include +#include "Budget.h" +using namespace std; + +int main() +{ + int count; // Loop counter + double mainOfficeRequest; // Main office budget request + const int NUM_DIVISIONS = 4; // Number of divisions + + // Get the main office's budget request. + // Note that no instances of the Budget class have been defined. + cout << "Enter the main office's budget request: "; + cin >> mainOfficeRequest; + Budget::mainOffice(mainOfficeRequest); + + Budget divisions[NUM_DIVISIONS]; // An array of Budget objects. + + // Get the budget requests for each division. + for (count = 0; count < NUM_DIVISIONS; count++) + { + double budgetAmount; + cout << "Enter the budget request for division "; + cout << (count + 1) << ": "; + cin >> budgetAmount; + divisions[count].addBudget(budgetAmount); + } + + // Display the budget requests and the corporate budget. + cout << fixed << showpoint << setprecision(2); + cout << "\nHere are the division budget requests:\n"; + for (count = 0; count < NUM_DIVISIONS; count++) + { + cout << "\tDivision " << (count + 1) << "\t$ "; + cout << divisions[count].getDivisionBudget() << endl; + } + cout << "\tTotal Budget Requests:\t$ "; + cout << divisions[0].getCorpBudget() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Auxil.cpp b/SourceCode/chapter 14/Budget Version 3/Auxil.cpp new file mode 100755 index 0000000..01b4c02 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Auxil.cpp @@ -0,0 +1,15 @@ +#include "Auxil.h" +#include "Budget.h" + +//*********************************************************** +// Definition of member function mainOffice. * +// This function is declared a friend by the Budget class. * +// It adds the value of argument b to the static corpBudget * +// member variable of the Budget class. * +//*********************************************************** + +void AuxiliaryOffice::addBudget(double b, Budget &div) +{ + auxBudget += b; + div.corpBudget += b; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Auxil.h b/SourceCode/chapter 14/Budget Version 3/Auxil.h new file mode 100755 index 0000000..6476d81 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Auxil.h @@ -0,0 +1,22 @@ +#ifndef AUXIL_H +#define AUXIL_H + +class Budget; // Forward declaration of Budget class + +// Aux class declaration + +class AuxiliaryOffice +{ +private: + double auxBudget; +public: + AuxiliaryOffice() + { auxBudget = 0; } + + double getDivisionBudget() const + { return auxBudget; } + + void addBudget(double, Budget &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Budget.cpp b/SourceCode/chapter 14/Budget Version 3/Budget.cpp new file mode 100755 index 0000000..390b5cd --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Budget.cpp @@ -0,0 +1,13 @@ +#include "Budget.h" +double Budget::corpBudget = 0; // Definition of static member variable + +//********************************************************** +// Definition of static member function mainOffice. * +// This function adds the main office's budget request to * +// the corpBudget variable. * +//********************************************************** + +void Budget::mainOffice(double moffice) +{ + corpBudget += moffice; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Budget.h b/SourceCode/chapter 14/Budget Version 3/Budget.h new file mode 100755 index 0000000..1d81296 --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Budget.h @@ -0,0 +1,32 @@ +#ifndef BUDGET_H +#define BUDGET_H +#include "Auxil.h" + +// Budget class declaration +class Budget +{ +private: + static double corpBudget; // Static member variable + double divisionBudget; // Instance member variable +public: + Budget() + { divisionBudget = 0; } + + void addBudget(double b) + { divisionBudget += b; + corpBudget += b; } + + double getDivisionBudget() const + { return divisionBudget; } + + double getCorpBudget() const + { return corpBudget; } + + // Static member function + static void mainOffice(double); + + // Friend function + friend void AuxiliaryOffice::addBudget(double, Budget &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Budget Version 3/Pr14-4.cpp b/SourceCode/chapter 14/Budget Version 3/Pr14-4.cpp new file mode 100755 index 0000000..f99637f --- /dev/null +++ b/SourceCode/chapter 14/Budget Version 3/Pr14-4.cpp @@ -0,0 +1,53 @@ +// This program demonstrates a static member function. +#include +#include +#include "Budget.h" +using namespace std; + +int main() +{ + int count; // Loop counter + double mainOfficeRequest; // Main office budget request + const int NUM_DIVISIONS = 4; // Number of divisions + + // Get the main office's budget request. + cout << "Enter the main office's budget request: "; + cin >> mainOfficeRequest; + Budget::mainOffice(mainOfficeRequest); + + Budget divisions[NUM_DIVISIONS]; // Array of Budget objects. + AuxiliaryOffice auxOffices[4]; // Array of AuxiliaryOffice + + // Get the budget requests for each division + // and their auxiliary offices. + for (count = 0; count < NUM_DIVISIONS; count++) + { + double budgetAmount; // To hold input + + // Get the request for the division office. + cout << "Enter the budget request for division "; + cout << (count + 1) << ": "; + cin >> budgetAmount; + divisions[count].addBudget(budgetAmount); + + // Get the request for the auxiliary office. + cout << "Enter the budget request for that division's\n"; + cout << "auxiliary office: "; + cin >> budgetAmount; + auxOffices[count].addBudget(budgetAmount, divisions[count]); + } + + // Display the budget requests and the corporate budget. + cout << fixed << showpoint << setprecision(2); + cout << "\nHere are the division budget requests:\n"; + for (count = 0; count < NUM_DIVISIONS; count++) + { + cout << "\tDivision " << (count + 1) << "\t\t$"; + cout << divisions[count].getDivisionBudget() << endl; + cout << "\tAuxiliary office:\t$"; + cout << auxOffices[count].getDivisionBudget() << endl << endl; + } + cout << "Total Budget Requests:\t$ "; + cout << divisions[0].getCorpBudget() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/ChoHan/Dealer.cpp b/SourceCode/chapter 14/ChoHan/Dealer.cpp new file mode 100755 index 0000000..8f15d8c --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Dealer.cpp @@ -0,0 +1,72 @@ +// Implementation file for the Dealer class +#include "Dealer.h" +#include "Die.h" +#include +using namespace std; + +//****************************************** +// Constructor * +//****************************************** +Dealer::Dealer() +{ + // Set the intial dice values to 0. + // (We will not use these values.) + die1Value = 0; + die2Value = 0; +} + +//****************************************** +// The rollDice member function rolls the * +// dice and saves their values. * +//****************************************** +void Dealer::rollDice() +{ + // Roll the dice. + die1.roll(); + die2.roll(); + + // Save the dice values. + die1Value = die1.getValue(); + die2Value = die2.getValue(); +} + +//****************************************** +// The getChoOrHan member function returns * +// the result of the dice roll, Cho (even) * +// or Han (odd). * +//****************************************** +string Dealer::getChoOrHan() +{ + string result; // To hold the result + + // Get the sum of the dice. + int sum = die1Value + die2Value; + + // Determine even or odd. + if (sum % 2 == 0) + result = "Cho (even)"; + else + result = "Han (odd)"; + + // Return the result. + return result; +} + +//******************************************* +// The getDie1Value member function returns * +// the value of die #1. * +//******************************************* +int Dealer::getDie1Value() +{ + return die1Value; +} + +//******************************************* +// The getDie2Value member function returns * +// the value of die #2. * +//******************************************* +int Dealer::getDie2Value() +{ + return die2Value; +} + diff --git a/SourceCode/chapter 14/ChoHan/Dealer.h b/SourceCode/chapter 14/ChoHan/Dealer.h new file mode 100755 index 0000000..7c2db6d --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Dealer.h @@ -0,0 +1,24 @@ +// Specification file for the Dealer class +#ifndef DEALER_H +#define DEALER_H +#include +#include "Die.h" +using namespace std; + +class Dealer +{ +private: + Die die1; // Object for die #1 + Die die2; // Object for die #2 + int die1Value; // Value of die #1 + int die2Value; // Value of die #2 + +public: + Dealer(); // Constructor + void rollDice(); // To roll the dice + string getChoOrHan(); // To get the result (Cho or Han) + int getDie1Value(); // To get the value of die #1 + int getDie2Value(); // To get the value of die #2 +}; +#endif + diff --git a/SourceCode/chapter 14/ChoHan/Player.cpp b/SourceCode/chapter 14/ChoHan/Player.cpp new file mode 100755 index 0000000..2a26f1d --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Player.cpp @@ -0,0 +1,80 @@ +// Implementation file for the Player class +#include "Player.h" +#include +#include +#include +using namespace std; + +//********************************************** +// Constructor * +//********************************************** +Player::Player(string playerName) +{ + // Seed the random number generator. + srand(time(0)); + + name = playerName; + guess = ""; + points = 0; +} + +//********************************************** +// The makeGuess member function causes the * +// player to make a guess, either "Cho (even)" * +// or "Han (odd)". * +//********************************************** +void Player::makeGuess() +{ + const int MIN_VALUE = 0; + const int MAX_VALUE = 1; + + int guessNumber; // For the user's guess + + // Get a random number, either 0 or 1. + guessNumber = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + + // Convert the random number to Cho or Han. + if (guessNumber == 0) + guess = "Cho (even)"; + else + guess = "Han (odd)"; +} + +//********************************************** +// The addPoints member function adds a * +// specified number of points to the player's * +// current balance. * +//********************************************** +void Player::addPoints(int newPoints) +{ + points += newPoints; +} + +//********************************************** +// The getName member function returns a * +// player's name. * +//********************************************** +string Player::getName() +{ + return name; +} + +//********************************************** +// The getGuess member function returns a * +// player's guess. * +//********************************************** +string Player::getGuess() +{ + return guess; +} + +//********************************************** +// The getPoints member function returns a * +// player's points. * +//********************************************** +int Player::getPoints() +{ + return points; +} + + diff --git a/SourceCode/chapter 14/ChoHan/Player.h b/SourceCode/chapter 14/ChoHan/Player.h new file mode 100755 index 0000000..b000146 --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Player.h @@ -0,0 +1,22 @@ +// Specification file for the Player class +#ifndef PLAYER_H +#define PLAYER_H +#include +using namespace std; + +class Player +{ +private: + string name; // The player's name + string guess; // The player's guess + int points; // The player's points + +public: + Player(string); // Constructor + void makeGuess(); // Causes player to make a guess + void addPoints(int); // Adds points to the player + string getName(); // Returns the player's name + string getGuess(); // Returns the player's guess + int getPoints(); // Returns the player's points +}; +#endif diff --git a/SourceCode/chapter 14/ChoHan/Pr14-17.cpp b/SourceCode/chapter 14/ChoHan/Pr14-17.cpp new file mode 100755 index 0000000..fd776a3 --- /dev/null +++ b/SourceCode/chapter 14/ChoHan/Pr14-17.cpp @@ -0,0 +1,133 @@ +// This program simulates the game of Cho-Han. +#include +#include +#include "Dealer.h" +#include "Player.h" +using namespace std; + +// Function prototypes +void roundResults(Dealer &, Player &, Player &); +void checkGuess(Player &, Dealer &); +void displayGrandWinner(Player, Player); + +int main() +{ + const int MAX_ROUNDS = 5; // Number of rounds + string player1Name; // First player's name + string player2Name; // Second player's name + + // Get the player's names. + cout << "Enter the first player's name: "; + cin >> player1Name; + cout << "Enter the second player's name: "; + cin >> player2Name; + + // Create the dealer. + Dealer dealer; + + // Create the two players. + Player player1(player1Name); + Player player2(player2Name); + + // Play the rounds. + for (int round = 0; round < MAX_ROUNDS; round++) + { + cout << "----------------------------\n"; + cout << "Now playing round " << (round + 1) + << endl; + + // Roll the dice. + dealer.rollDice(); + + // The players make their guesses. + player1.makeGuess(); + player2.makeGuess(); + + // Determine the winner of this round. + roundResults(dealer, player1, player2); + } + + // Display the grand winner. + displayGrandWinner(player1, player2); + return 0; +} + +//*************************************************** +// The roundResults function detremines the results * +// of the current round. * +//*************************************************** +void roundResults(Dealer &dealer, Player &player1, Player &player2) +{ + // Show the dice values. + cout << "The dealer rolled " << dealer.getDie1Value() + << " and " << dealer.getDie2Value() << endl; + + // Show the result (Cho or Han). + cout << "Result: " << dealer.getChoOrHan() << endl; + + // Check each player's guess and award points. + checkGuess(player1, dealer); + checkGuess(player2, dealer); +} + +//*************************************************** +// The checkGuess function checks a player's guess * +// against the dealer's result. * +//*************************************************** +void checkGuess(Player &player, Dealer &dealer) +{ + const int POINTS_TO_ADD = 1; // Points to award winner + + // Get the player's guess + string guess = player.getGuess(); + + // Get the result (Cho or Han). + string choHanResult = dealer.getChoOrHan(); + + // Display the player's guess. + cout << "The player " << player.getName() + << " guessed " << player.getGuess() << endl; + + // Award points if the player guessed correctly. + if (guess == choHanResult) + { + player.addPoints(POINTS_TO_ADD); + cout << "Awarding " << POINTS_TO_ADD + << " point(s) to " << player.getName() + << endl; + } +} + +//*************************************************** +// The displayGrandWinner function displays the * +// game's grand winner. * +//*************************************************** +void displayGrandWinner(Player player1, Player player2) +{ + cout << "----------------------------\n"; + cout << "Game over. Here are the results:\n"; + + // Display player #1's results. + cout << player1.getName() << ": " + << player1.getPoints() << " points\n"; + + // Display player #2's results. + cout << player2.getName() << ": " + << player2.getPoints() << " points\n"; + + // Determine the grand winner. + if (player1.getPoints() > player2.getPoints()) + { + cout << player1.getName() + << " is the grand winner!\n"; + } + else if (player2.getPoints() > player1.getPoints()) + { + cout << player2.getName() + << " is the grand winner!\n"; + } + else + { + cout << "Both players are tied!\n"; + } +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Course.h b/SourceCode/chapter 14/Course.h new file mode 100755 index 0000000..262062b --- /dev/null +++ b/SourceCode/chapter 14/Course.h @@ -0,0 +1,39 @@ +#ifndef COURSE +#define COURSE +#include +#include +#include "Instructor.h" +#include "TextBook.h" +using namespace std; + +class Course +{ +private: + string courseName; // Course name + Instructor instructor; // Instructor + TextBook textbook; // Textbook +public: + // Constructor + Course(string course, string instrLastName, + string instrFirstName, string instrOffice, + string textTitle, string author, + string publisher) + { // Assign the course name. + courseName = course; + + // Assign the instructor. + instructor.set(instrLastName, instrFirstName, instrOffice); + + // Assign the textbook. + textbook.set(textTitle, author, publisher); } + + // print function + void print() const + { cout << "Course name: " << courseName << endl << endl; + cout << "Instructor Information:\n"; + instructor.print(); + cout << "\nTextbook Information:\n"; + textbook.print(); + cout << endl; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 1/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.cpp new file mode 100755 index 0000000..8e26d32 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.cpp @@ -0,0 +1,55 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 1/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.h new file mode 100755 index 0000000..6c6782d --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 1/FeetInches.h @@ -0,0 +1,40 @@ +#ifndef FEETINCHES_H +#define FEETINCHES_H + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 1/Pr14-8.cpp b/SourceCode/chapter 14/FeetInches Version 1/Pr14-8.cpp new file mode 100755 index 0000000..f62bec4 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 1/Pr14-8.cpp @@ -0,0 +1,48 @@ +// This program demonstrates the FeetInches class's overloaded +// + and - operators. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + int feet, inches; // To hold input for feet and inches + + // Create three FeetInches objects. The default arguments + // for the constructor will be used. + FeetInches first, second, third; + + // Get a distance from the user. + cout << "Enter a distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in the first object. + first.setFeet(feet); + first.setInches(inches); + + // Get another distance from the user. + cout << "Enter another distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in second. + second.setFeet(feet); + second.setInches(inches); + + // Assign first + second to third. + third = first + second; + + // Display the result. + cout << "first + second = "; + cout << third.getFeet() << " feet, "; + cout << third.getInches() << " inches.\n"; + + // Assign first - second to third. + third = first - second; + + // Display the result. + cout << "first - second = "; + cout << third.getFeet() << " feet, "; + cout << third.getInches() << " inches.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 2/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.cpp new file mode 100755 index 0000000..2b54e39 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.cpp @@ -0,0 +1,83 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator++() +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator++(int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 2/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.h new file mode 100755 index 0000000..4190eb5 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 2/FeetInches.h @@ -0,0 +1,42 @@ +#ifndef FEETINCHES_H +#define FEETINCHES_H + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 2/Pr14-9.cpp b/SourceCode/chapter 14/FeetInches Version 2/Pr14-9.cpp new file mode 100755 index 0000000..c6787fb --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 2/Pr14-9.cpp @@ -0,0 +1,41 @@ +// This program demonstrates the FeetInches class' overloaded +// prefix and postfix ++ operators. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + int count; // Loop counter + + // Define a FeetInches object with the default + // value of 0 feet, 0 inches. + FeetInches first; + + // Define a FeetInches object with 1 foot 5 inches. + FeetInches second(1, 5); + + // Use the prefix ++ operator. + cout << "Demonstrating prefix ++ operator.\n"; + for (count = 0; count < 12; count++) + { + first = ++second; + cout << "first: " << first.getFeet() << " feet, "; + cout << first.getInches() << " inches. "; + cout << "second: " << second.getFeet() << " feet, "; + cout << second.getInches() << " inches.\n"; + } + + // Use the postfix ++ operator. + cout << "\nDemonstrating postfix ++ operator.\n"; + for (count = 0; count < 12; count++) + { + first = second++; + cout << "first: " << first.getFeet() << " feet, "; + cout << first.getInches() << " inches. "; + cout << "second: " << second.getFeet() << " feet, "; + cout << second.getInches() << " inches.\n"; + } + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 3/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.cpp new file mode 100755 index 0000000..7fff308 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.cpp @@ -0,0 +1,138 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 3/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.h new file mode 100755 index 0000000..9e0e41a --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 3/FeetInches.h @@ -0,0 +1,46 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 3/Pr14-10.cpp b/SourceCode/chapter 14/FeetInches Version 3/Pr14-10.cpp new file mode 100755 index 0000000..a3a3c5c --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 3/Pr14-10.cpp @@ -0,0 +1,40 @@ +// This program demonstrates the FeetInches class's overloaded +// relational operators. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + int feet, inches; // To hold input for feet and inches + + // Create two FeetInches objects. The default arguments + // for the constructor will be used. + FeetInches first, second; + + // Get a distance from the user. + cout << "Enter a distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in first. + first.setFeet(feet); + first.setInches(inches); + + // Get another distance. + cout << "Enter another distance in feet and inches: "; + cin >> feet >> inches; + + // Store the distance in second. + second.setFeet(feet); + second.setInches(inches); + + // Compare the two objects. + if (first == second) + cout << "first is equal to second.\n"; + if (first > second) + cout << "first is greater than second.\n"; + if (first < second) + cout << "first is less than second.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 4/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.cpp new file mode 100755 index 0000000..ea33f56 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.cpp @@ -0,0 +1,170 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 4/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.h new file mode 100755 index 0000000..8c43f5f --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 4/FeetInches.h @@ -0,0 +1,58 @@ +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 4/Pr14-11.cpp b/SourceCode/chapter 14/FeetInches Version 4/Pr14-11.cpp new file mode 100755 index 0000000..e8a32bd --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 4/Pr14-11.cpp @@ -0,0 +1,23 @@ +// This program demonstrates the << and >> operators, +// overloaded to work with the FeetInches class. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + FeetInches first, second; // Define two objects. + + // Get a distance for the first object. + cout << "Enter a distance in feet and inches.\n"; + cin >> first; + + // Get a distance for the second object. + cout << "Enter another distance in feet and inches.\n"; + cin >> second; + + // Display the values in the objects. + cout << "The values you entered are:\n"; + cout << first << " and " << second << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 5/FeetInches.cpp b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.cpp new file mode 100755 index 0000000..d47f51e --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.cpp @@ -0,0 +1,193 @@ +// Implementation file for the FeetInches class +#include // Needed for abs() +#include "FeetInches.h" + +//************************************************************ +// Definition of member function simplify. This function * +// checks for values in the inches member greater than * +// twelve or less than zero. If such a value is found, * +// the numbers in feet and inches are adjusted to conform * +// to a standard feet & inches expression. For example, * +// 3 feet 14 inches would be adjusted to 4 feet 2 inches and * +// 5 feet -2 inches would be adjusted to 4 feet 10 inches. * +//************************************************************ + +void FeetInches::simplify() +{ + if (inches >= 12) + { + feet += (inches / 12); + inches = inches % 12; + } + else if (inches < 0) + { + feet -= ((abs(inches) / 12) + 1); + inches = 12 - (abs(inches) % 12); + } +} + +//********************************************** +// Overloaded binary + operator. * +//********************************************** + +FeetInches FeetInches::operator + (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches + right.inches; + temp.feet = feet + right.feet; + temp.simplify(); + return temp; +} + + +//********************************************** +// Overloaded binary - operator. * +//********************************************** + +FeetInches FeetInches::operator - (const FeetInches &right) +{ + FeetInches temp; + + temp.inches = inches - right.inches; + temp.feet = feet - right.feet; + temp.simplify(); + return temp; +} + +//************************************************************* +// Overloaded prefix ++ operator. Causes the inches member to * +// be incremented. Returns the incremented object. * +//************************************************************* + +FeetInches FeetInches::operator ++ () +{ + ++inches; + simplify(); + return *this; +} + +//*************************************************************** +// Overloaded postfix ++ operator. Causes the inches member to * +// be incremented. Returns the value of the object before the * +// increment. * +//*************************************************************** + +FeetInches FeetInches::operator ++ (int) +{ + FeetInches temp(feet, inches); + + inches++; + simplify(); + return temp; +} + +//************************************************************ +// Overloaded > operator. Returns true if the current object * +// is set to a value greater than that of right. * +//************************************************************ + +bool FeetInches::operator > (const FeetInches &right) +{ + bool status; + + if (feet > right.feet) + status = true; + else if (feet == right.feet && inches > right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************ +// Overloaded < operator. Returns true if the current object * +// is set to a value less than that of right. * +//************************************************************ + +bool FeetInches::operator < (const FeetInches &right) +{ + bool status; + + if (feet < right.feet) + status = true; + else if (feet == right.feet && inches < right.inches) + status = true; + else + status = false; + + return status; +} + +//************************************************************* +// Overloaded == operator. Returns true if the current object * +// is set to a value equal to that of right. * +//************************************************************* + +bool FeetInches::operator == (const FeetInches &right) +{ + bool status; + + if (feet == right.feet && inches == right.inches) + status = true; + else + status = false; + + return status; +} + +//******************************************************** +// Overloaded << operator. Gives cout the ability to * +// directly display FeetInches objects. * +//******************************************************** + +ostream &operator<<(ostream &strm, const FeetInches &obj) +{ + strm << obj.feet << " feet, " << obj.inches << " inches"; + return strm; +} + +//******************************************************** +// Overloaded >> operator. Gives cin the ability to * +// store user input directly into FeetInches objects. * +//******************************************************** + +istream &operator >> (istream &strm, FeetInches &obj) +{ + // Prompt the user for the feet. + cout << "Feet: "; + strm >> obj.feet; + + // Prompt the user for the inches. + cout << "Inches: "; + strm >> obj.inches; + + // Normalize the values. + obj.simplify(); + + return strm; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to a double. * +//************************************************************* + +FeetInches::operator double() +{ + double temp = feet; + + temp += (inches / 12.0); + return temp; +} + +//************************************************************* +// Conversion function to convert a FeetInches object * +// to an int. * +//************************************************************* + +FeetInches:: operator int() +{ + return feet; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 5/FeetInches.h b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.h new file mode 100755 index 0000000..9c92f58 --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 5/FeetInches.h @@ -0,0 +1,63 @@ +// Specification file for the FeetInches class +#ifndef FEETINCHES_H +#define FEETINCHES_H + +#include +using namespace std; + +class FeetInches; // Forward Declaration + +// Function Prototypes for Overloaded Stream Operators +ostream &operator << (ostream &, const FeetInches &); +istream &operator >> (istream &, FeetInches &); + +// The FeetInches class holds distances or measurements +// expressed in feet and inches. + +class FeetInches +{ +private: + int feet; // To hold a number of feet + int inches; // To hold a number of inches + void simplify(); // Defined in FeetInches.cpp +public: + // Constructor + FeetInches(int f = 0, int i = 0) + { feet = f; + inches = i; + simplify(); } + + // Mutator functions + void setFeet(int f) + { feet = f; } + + void setInches(int i) + { inches = i; + simplify(); } + + // Accessor functions + int getFeet() const + { return feet; } + + int getInches() const + { return inches; } + + // Overloaded operator functions + FeetInches operator + (const FeetInches &); // Overloaded + + FeetInches operator - (const FeetInches &); // Overloaded - + FeetInches operator ++ (); // Prefix ++ + FeetInches operator ++ (int); // Postfix ++ + bool operator > (const FeetInches &); // Overloaded > + bool operator < (const FeetInches &); // Overloaded < + bool operator == (const FeetInches &); // Overloaded == + + // Conversion functions + operator double(); + operator int(); + + // Friends + friend ostream &operator << (ostream &, const FeetInches &); + friend istream &operator >> (istream &, FeetInches &); +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/FeetInches Version 5/Pr14-14.cpp b/SourceCode/chapter 14/FeetInches Version 5/Pr14-14.cpp new file mode 100755 index 0000000..c6d6a3c --- /dev/null +++ b/SourceCode/chapter 14/FeetInches Version 5/Pr14-14.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the the FeetInches class's +// conversion functions. +#include +#include "FeetInches.h" +using namespace std; + +int main() +{ + double d; // To hold double input + int i; // To hold int input + + // Define a FeetInches object. + FeetInches distance; + + // Get a distance from the user. + cout << "Enter a distance in feet and inches:\n"; + cin >> distance; + + // Convert the distance object to a double. + d = distance; + + // Convert the distance object to an int. + i = distance; + + // Display the values. + cout << "The value " << distance; + cout << " is equivalent to " << d << " feet\n"; + cout << "or " << i << " feet, rounded down.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Instructor.h b/SourceCode/chapter 14/Instructor.h new file mode 100755 index 0000000..59846b6 --- /dev/null +++ b/SourceCode/chapter 14/Instructor.h @@ -0,0 +1,36 @@ +#ifndef INSTRUCTOR +#define INSTRUCTOR +#include +#include +using namespace std; + +// Instructor class +class Instructor +{ +private: + string lastName; // Last name + string firstName; // First name + string officeNumber; // Office number +public: + // The default constructor stores empty strings + // in the string objects. + Instructor() + { set("", "", ""); } + + // Constructor + Instructor(string lname, string fname, string office) + { set(lname, fname, office); } + + // set function + void set(string lname, string fname, string office) + { lastName = lname; + firstName = fname; + officeNumber = office; } + + // print function + void print() const + { cout << "Last name: " << lastName << endl; + cout << "First name: " << firstName << endl; + cout << "Office number: " << officeNumber << endl; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/IntArray.cpp b/SourceCode/chapter 14/IntArray.cpp new file mode 100755 index 0000000..3729109 --- /dev/null +++ b/SourceCode/chapter 14/IntArray.cpp @@ -0,0 +1,64 @@ +// Implementation file for the IntArray class +#include +#include // For the exit function +#include "IntArray.h" +using namespace std; + +//******************************************************* +// Constructor for IntArray class. Sets the size of the * +// array and allocates memory for it. * +//******************************************************* + +IntArray::IntArray(int s) +{ + arraySize = s; + aptr = new int [s]; + for (int count = 0; count < arraySize; count++) + *(aptr + count) = 0; +} + +//****************************************************** +// Copy Constructor for IntArray class. * +//****************************************************** + +IntArray::IntArray(const IntArray &obj) +{ + arraySize = obj.arraySize; + aptr = new int [arraySize]; + for(int count = 0; count < arraySize; count++) + *(aptr + count) = *(obj.aptr + count); +} + +//****************************************************** +// Destructor for IntArray class. * +//****************************************************** + +IntArray::~IntArray() +{ + if (arraySize > 0) + delete [] aptr; +} + +//*********************************************************** +// subscriptError function. Displays an error message and * +// terminates the program when a subscript is out of range. * +//*********************************************************** + +void IntArray::subscriptError() +{ + cout << "ERROR: Subscript out of range.\n"; + exit(0); +} + +//******************************************************* +// Overloaded [] operator. The argument is a subscript. * +// This function returns a reference to the element * +// in the array indexed by the subscript. * +//******************************************************* + +int &IntArray::operator[](const int &sub) +{ + if (sub < 0 || sub >= arraySize) + subscriptError(); + return aptr[sub]; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/IntArray.h b/SourceCode/chapter 14/IntArray.h new file mode 100755 index 0000000..bd1c7bc --- /dev/null +++ b/SourceCode/chapter 14/IntArray.h @@ -0,0 +1,21 @@ +// Specification file for the IntArray class +#ifndef INTARRAY_H +#define INTARRAY_H + +class IntArray +{ +private: + int *aptr; // Pointer to the array + int arraySize; // Holds the array size + void subscriptError(); // Handles invalid subscripts +public: + IntArray(int); // Constructor + IntArray(const IntArray &); // Copy constructor + ~IntArray(); // Destructor + + int size() const // Returns the array size + { return arraySize; } + + int &operator[](const int &); // Overloaded [] operator +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-1.cpp b/SourceCode/chapter 14/Pr14-1.cpp new file mode 100755 index 0000000..84298b2 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-1.cpp @@ -0,0 +1,17 @@ +// This program demonstrates a static member variable. +#include +#include "Tree.h" +using namespace std; + +int main() +{ + // Define three Tree objects. + Tree oak; + Tree elm; + Tree pine; + + // Display the number of Tree objects we have. + cout << "We have " << pine.getObjectCount() + << " trees in our program!\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-12.cpp b/SourceCode/chapter 14/Pr14-12.cpp new file mode 100755 index 0000000..43e6f5f --- /dev/null +++ b/SourceCode/chapter 14/Pr14-12.cpp @@ -0,0 +1,41 @@ +// This program demonstrates an overloaded [] operator. +#include +#include "IntArray.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Array size + + // Define an IntArray with 10 elements. + IntArray table(SIZE); + + // Store values in the array. + for (int x = 0; x < SIZE; x++) + table[x] = (x * 2); + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + // Use the standard + operator on array elements. + for (x = 0; x < SIZE; x++) + table[x] = table[x] + 5; + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + // Use the standard ++ operator on array elements. + for (x = 0; x < SIZE; x++) + table[x]++; + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-13.cpp b/SourceCode/chapter 14/Pr14-13.cpp new file mode 100755 index 0000000..48f59ef --- /dev/null +++ b/SourceCode/chapter 14/Pr14-13.cpp @@ -0,0 +1,26 @@ +// This program demonstrates the IntArray class's bounds-checking ability. +#include +#include "IntArray.h" +using namespace std; + +int main() +{ + const int SIZE = 10; // Array size + + // Define an IntArray with 10 elements. + IntArray table(SIZE); + + // Store values in the array. + for (int x = 0; x < SIZE; x++) + table[x] = x; + + // Display the values in the array. + for (x = 0; x < SIZE; x++) + cout << table[x] << " "; + cout << endl; + + // Attempt to use an invalid subscript... + cout << "Now attempting to use an invalid subscript.\n"; + table[SIZE + 1] = 0; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-15.cpp b/SourceCode/chapter 14/Pr14-15.cpp new file mode 100755 index 0000000..7b57b22 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-15.cpp @@ -0,0 +1,15 @@ +// This program demonstrates the Course class. +#include "Course.h" + +int main() +{ + // Create a Course object. + Course myCourse("Intro to Computer Science", // Course name + "Kramer", "Shawn", "RH3010", // Instructor info + "Starting Out with C++", "Gaddis", // Textbook title and author + "Addison-Wesley"); // Textbook publisher + + // Display the course info. + myCourse.print(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-16.cpp b/SourceCode/chapter 14/Pr14-16.cpp new file mode 100755 index 0000000..728c5c8 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-16.cpp @@ -0,0 +1,36 @@ +// Stock trader program +#include +#include +#include "Stock.h" +#include "StockPurchase.h" +using namespace std; + +int main() +{ + int sharesToBuy; // Number of shares to buy + + // Create a Stock object for the company stock. The + // trading symbol is XYZ and the stock is currently + // priced at $9.62 per share. + Stock xyzCompany("XYZ", 9.62); + + // Display the symbol and current share price. + cout << setprecision(2) << fixed << showpoint; + cout << "XYZ Company's trading symbol is " + << xyzCompany.getSymbol() << endl; + cout << "The stock is currently $" + << xyzCompany.getSharePrice() + << " per share.\n"; + + // Get the number of shares to purchase. + cout << "How many shares do you want to buy? "; + cin >> sharesToBuy; + + // Create a StockPurchase object for the transaction. + StockPurchase buy(xyzCompany, sharesToBuy); + + // Display the cost of the transaction. + cout << "The cost of the transaction is $" + << buy.getCost() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Pr14-5.cpp b/SourceCode/chapter 14/Pr14-5.cpp new file mode 100755 index 0000000..17669f5 --- /dev/null +++ b/SourceCode/chapter 14/Pr14-5.cpp @@ -0,0 +1,28 @@ +// This program demonstrates memberwise assignment. +#include +#include "Rectangle.h" +using namespace std; + +int main() +{ + // Define two Rectangle objects. + Rectangle box1(10.0, 10.0); // width = 10.0, length = 10.0 + Rectangle box2 (20.0, 20.0); // width = 20.0, length = 20.0 + + // Display each object's width and length. + cout << "box1's width and length: " << box1.getWidth() + << " " << box1.getLength() << endl; + cout << "box2's width and length: " << box2.getWidth() + << " " << box2.getLength() << endl << endl; + + // Assign the members of box1 to box2. + box2 = box1; + + // Display each object's width and length again. + cout << "box1's width and length: " << box1.getWidth() + << " " << box1.getLength() << endl; + cout << "box2's width and length: " << box2.getWidth() + << " " << box2.getLength() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Rectangle.cpp b/SourceCode/chapter 14/Rectangle.cpp new file mode 100755 index 0000000..200f8fb --- /dev/null +++ b/SourceCode/chapter 14/Rectangle.cpp @@ -0,0 +1,46 @@ +// Implementation file for the Rectangle class. +// This version has a constructor that accepts arguments. +#include "Rectangle.h" // Needed for the Rectangle class +#include // Needed for cout +#include // Needed for the exit function +using namespace std; + +//*********************************************************** +// The constructor accepts arguments for width and length. * +//*********************************************************** + +Rectangle::Rectangle(double w, double len) +{ + width = w; + length = len; +} + +//*********************************************************** +// setWidth sets the value of the member variable width. * +//*********************************************************** + +void Rectangle::setWidth(double w) +{ + if (w >= 0) + width = w; + else + { + cout << "Invalid width\n"; + exit(EXIT_FAILURE); + } +} + +//*********************************************************** +// setLength sets the value of the member variable length. * +//*********************************************************** + +void Rectangle::setLength(double len) +{ + if (len >= 0) + length = len; + else + { + cout << "Invalid length\n"; + exit(EXIT_FAILURE); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Rectangle.h b/SourceCode/chapter 14/Rectangle.h new file mode 100755 index 0000000..ac8f474 --- /dev/null +++ b/SourceCode/chapter 14/Rectangle.h @@ -0,0 +1,25 @@ +// Specification file for the Rectangle class +// This version has a constructor. +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ + private: + double width; + double length; + public: + Rectangle(double, double); // Constructor + void setWidth(double); + void setLength(double); + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StaticDemo.cpp b/SourceCode/chapter 14/StaticDemo.cpp new file mode 100755 index 0000000..0edcd7b --- /dev/null +++ b/SourceCode/chapter 14/StaticDemo.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +class StaticDemo +{ +private: + int instanceVariable; // Instance variable + static int staticVariable; // Static variable +public: + void setInstanceVariable(int n) + { instanceVariable = n; } + + void setStaticVariable(int n) + { staticVariable = n; } + + int getInstanceVariable() + { return instanceVariable; } + + int getStaticVariable() + { return staticVariable; } +}; + +int StaticDemo::staticVariable; + +int main() +{ + StaticDemo demo1, demo2; + + // Use demo1 to store values in the instanceVariable + // and staticVariable members. + demo1.setInstanceVariable(1); + demo1.setStaticVariable(5); + + // Use demo2 to store a value in the instanceVariable + // member, but do not store a value in staticVariable. + demo2.setInstanceVariable(100); + + // Display the values in the demo1's member variables. + cout << "demo1's members are " + << demo1.getInstanceVariable() << " and " + << demo1.getStaticVariable() << endl; + + // Display the values in the demo2's member variables, + // including staticVariable. + cout << "demo2's members are " + << demo2.getInstanceVariable() << " and " + << demo2.getStaticVariable() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/Stock.h b/SourceCode/chapter 14/Stock.h new file mode 100755 index 0000000..6fd319e --- /dev/null +++ b/SourceCode/chapter 14/Stock.h @@ -0,0 +1,36 @@ +#ifndef STOCK +#define STOCK +#include +using namespace std; + +class Stock +{ +private: + string symbol; // Trading symbol of the stock + double sharePrice; // Current price per share +public: + // Default Constructor + Stock() + { set("", 0.0); } + + // Constructor + Stock(const string sym, double price) + { set(sym, price); } + + // Copy constructor + Stock(const Stock &obj) + { set(obj.symbol, obj.sharePrice); } + + // Mutator function + void set(string sym, double price) + { symbol = sym; + sharePrice = price; } + + // Accessor functions + string getSymbol() const + { return symbol; } + + double getSharePrice() const + { return sharePrice; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StockPurchase.h b/SourceCode/chapter 14/StockPurchase.h new file mode 100755 index 0000000..0a398df --- /dev/null +++ b/SourceCode/chapter 14/StockPurchase.h @@ -0,0 +1,25 @@ +#ifndef STOCK_PURCHASE +#define STOCK_PURCHASE +#include "Stock.h" + +class StockPurchase +{ +private: + Stock stock; // The stock that was purchased + int shares; // The number of shares +public: + // The default constructor sets shares to 0. The stock + // object is initialized by its default constructor. + StockPurchase() + { shares = 0; } + + // Constructor + StockPurchase(const Stock &stockObject, int numShares) + { stock = stockObject; + shares = numShares; } + + // Accessor function + double getCost() const + { return shares * stock.getSharePrice(); } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Verison 1/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Verison 1/StudentTestScores.h new file mode 100755 index 0000000..6eea4ef --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Verison 1/StudentTestScores.h @@ -0,0 +1,54 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 2/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Version 2/StudentTestScores.h new file mode 100755 index 0000000..28a08b4 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 2/StudentTestScores.h @@ -0,0 +1,62 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Copy constructor + StudentTestScores(const StudentTestScores &obj) + { studentName = obj.studentName; + numTestScores = obj. numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = obj.testScores[i]; } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 3/Pr14-6.cpp b/SourceCode/chapter 14/StudentTestScores Version 3/Pr14-6.cpp new file mode 100755 index 0000000..644019e --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 3/Pr14-6.cpp @@ -0,0 +1,41 @@ +// This program demonstrates the overloaded = operator +#include +#include "StudentTestScores.h" +using namespace std; + +// Function prototype +void displayStudent(StudentTestScores); + +int main() +{ + // Create a StudentTestScores object and + // assign test scores. + StudentTestScores student1("Kelly Thorton", 3); + student1.setTestScore(100.0, 0); + student1.setTestScore(95.0, 1); + student1.setTestScore(80, 2); + + // Create another StudentTestScore object + // with default test scores. + StudentTestScores student2("Jimmy Griffin", 5); + + // Assign the student1 object to student2 + student2 = student1; + + // Display both objects. They should + // contain the same data. + displayStudent(student1); + displayStudent(student2); + return 0; +} + +// The displayStudent function accepts a +// StudentTestScores object's data. +void displayStudent(StudentTestScores s) +{ + cout << "Name: " << s.getStudentName() << endl; + cout << "Test Scores: "; + for (int i = 0; i < s.getNumTestScores(); i++) + cout << s.getTestScore(i) << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 3/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Version 3/StudentTestScores.h new file mode 100755 index 0000000..083d344 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 3/StudentTestScores.h @@ -0,0 +1,71 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Copy constructor + StudentTestScores(const StudentTestScores &obj) + { studentName = obj.studentName; + numTestScores = obj. numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = obj.testScores[i]; } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } + + // Overloaded = operator + void operator=(const StudentTestScores &right) + { delete [] testScores; + studentName = right.studentName; + numTestScores = right.numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = right.testScores[i]; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 4/Pr14-7.cpp b/SourceCode/chapter 14/StudentTestScores Version 4/Pr14-7.cpp new file mode 100755 index 0000000..fd42776 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 4/Pr14-7.cpp @@ -0,0 +1,39 @@ +// This program demonstrates the overloaded = operator returning a value. +#include +#include "StudentTestScores.h" +using namespace std; + +// Function prototype +void displayStudent(StudentTestScores); + +int main() +{ + // Create a StudentTestScores object. + StudentTestScores student1("Kelly Thorton", 3); + student1.setTestScore(100.0, 0); + student1.setTestScore(95.0, 1); + student1.setTestScore(80, 2); + + // Create two more StudentTestScores objects. + StudentTestScores student2("Jimmy Griffin", 5); + StudentTestScores student3("Kristen Lee", 10); + + // Assign student1 to student2 and student3. + student3 = student2 = student1; + + // Display the objects. + displayStudent(student1); + displayStudent(student2); + displayStudent(student3); + return 0; +} + +// displayStudent function +void displayStudent(StudentTestScores s) +{ + cout << "Name: " << s.getStudentName() << endl; + cout << "Test Scores: "; + for (int i = 0; i < s.getNumTestScores(); i++) + cout << s.getTestScore(i) << " "; + cout << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 14/StudentTestScores Version 4/StudentTestScores.h b/SourceCode/chapter 14/StudentTestScores Version 4/StudentTestScores.h new file mode 100755 index 0000000..624a803 --- /dev/null +++ b/SourceCode/chapter 14/StudentTestScores Version 4/StudentTestScores.h @@ -0,0 +1,73 @@ +#ifndef STUDENTTESTSCORES_H +#define STUDENTTESTSCORES_H +#include +using namespace std; + +const double DEFAULT_SCORE = 0.0; + +class StudentTestScores +{ +private: + string studentName; // The student's name + double *testScores; // Points to array of test scores + int numTestScores; // Number of test scores + + // Private member function to create an + // array of test scores. + void createTestScoresArray(int size) + { numTestScores = size; + testScores = new double[size]; + for (int i = 0; i < size; i++) + testScores[i] = DEFAULT_SCORE; } + +public: + // Constructor + StudentTestScores(string name, int numScores) + { studentName = name; + createTestScoresArray(numScores); } + + // Copy constructor + StudentTestScores(const StudentTestScores &obj) + { studentName = obj.studentName; + numTestScores = obj. numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = obj.testScores[i]; } + + // Destructor + ~StudentTestScores() + { delete [] testScores; } + + // The setTestScore function sets a specific + // test score's value. + void setTestScore(double score, int index) + { testScores[index] = score; } + + // Set the student's name. + void setStudentName(string name) + { studentName = name; } + + // Get the student's name. + string getStudentName() const + { return studentName; } + + // Get the number of test scores. + int getNumTestScores() + { return numTestScores; } + + // Get a specific test score. + double getTestScore(int index) const + { return testScores[index]; } + + // Overloaded = operator + const StudentTestScores operator=(const StudentTestScores &right) + { delete [] testScores; + studentName = right.studentName; + numTestScores = right.numTestScores; + testScores = new double[numTestScores]; + for (int i = 0; i < numTestScores; i++) + testScores[i] = right.testScores[i]; + return *this; } + +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/TextBook.h b/SourceCode/chapter 14/TextBook.h new file mode 100755 index 0000000..852726e --- /dev/null +++ b/SourceCode/chapter 14/TextBook.h @@ -0,0 +1,36 @@ +#ifndef TEXTBOOK +#define TEXTBOOK +#include +#include +using namespace std; + +// TextBook class +class TextBook +{ +private: + string title; // Book title + string author; // Author name + string publisher; // Publisher name +public: + // The default constructor stores empty strings + // in the string objects. + TextBook() + { set("", "", ""); } + + // Constructor + TextBook(string textTitle, string auth, string pub) + { set(textTitle, auth, pub); } + + // set function + void set(string textTitle, string auth, string pub) + { title = textTitle; + author = auth; + publisher = pub; } + + // print function + void print() const + { cout << "Title: " << title << endl; + cout << "Author: " << author << endl; + cout << "Publisher: " << publisher << endl; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 14/Tree.h b/SourceCode/chapter 14/Tree.h new file mode 100755 index 0000000..fbb12e6 --- /dev/null +++ b/SourceCode/chapter 14/Tree.h @@ -0,0 +1,18 @@ +// Tree class +class Tree +{ +private: + static int objectCount; // Static member variable. +public: + // Constructor + Tree() + { objectCount++; } + + // Accessor function for objectCount + int getObjectCount() const + { return objectCount; } +}; + +// Definition of the static member variable, written +// outside the class. +int Tree::objectCount = 0; \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Automobile.h b/SourceCode/chapter 15/Automobile/Automobile.h new file mode 100755 index 0000000..11fe7ee --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Automobile.h @@ -0,0 +1,45 @@ +#ifndef AUTOMOBILE_H +#define AUTOMOBILE_H +#include +using namespace std; + +// The Automobile class holds general data +// about an automobile in inventory. +class Automobile +{ +private: + string make; // The auto's make + int model; // The auto's year model + int mileage; // The auto's mileage + double price; // The auto's price + +public: + // Default constructor + Automobile() + { make = ""; + model = 0; + mileage = 0; + price = 0.0; } + + // Constructor + Automobile(string autoMake, int autoModel, + int autoMileage, double autoPrice) + { make = autoMake; + model = autoModel; + mileage = autoMileage; + price = autoPrice; } + + // Accessors + string getMake() const + { return make; } + + int getModel() const + { return model; } + + int getMileage() const + { return mileage; } + + double getPrice() const + { return price; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Car.h b/SourceCode/chapter 15/Automobile/Car.h new file mode 100755 index 0000000..95ea88c --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Car.h @@ -0,0 +1,28 @@ +#ifndef CAR_H +#define CAR_H +#include "Automobile.h" +#include +using namespace std; + +// The Car class represents a car. +class Car : public Automobile +{ +private: + int doors; + +public: + // Default constructor + Car() : Automobile() + { doors = 0; } + + // Constructor #2 + Car(string carMake, int carModel, int carMileage, + double carPrice, int carDoors) : + Automobile(carMake, carModel, carMileage, carPrice) + { doors = carDoors; } + + // Accessor for doors attribute + int getDoors() + { return doors; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Pr15-6.cpp b/SourceCode/chapter 15/Automobile/Pr15-6.cpp new file mode 100755 index 0000000..6ae371b --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Pr15-6.cpp @@ -0,0 +1,48 @@ +// This program demonstrates the Car, Truck, and SUV +// classes that are derived from the Automobile class. +#include +#include +#include "Car.h" +#include "Truck.h" +#include "SUV.h" +using namespace std; + +int main() +{ + // Create a Car object for a used 2007 BMW with + // 50,000 miles, priced at $15,000, with 4 doors. + Car car("BMW", 2007, 50000, 15000.0, 4); + + // Create a Truck object for a used 2006 Toyota + // pickup with 40,000 miles, priced at $12,000, + // with 4-wheel drive. + Truck truck("Toyota", 2006, 40000, 12000.0, "4WD"); + + // Create an SUV object for a used 2005 Volvo + // with 30,000 miles, priced at $18,000, with + // 5 passenger capacity. + SUV suv("Volvo", 2005, 30000, 18000.00, 5); + + // Display the automobiles we have in inventory. + cout << fixed << showpoint << setprecision(2); + cout << "We have the following car in inventory:\n" + << car.getModel() << " " << car.getMake() + << " with " << car.getDoors() << " doors and " + << car.getMileage() << " miles.\nPrice: $" + << car.getPrice() << endl << endl; + + cout << "We have the following truck in inventory:\n" + << truck.getModel() << " " << truck.getMake() + << " with " << truck.getDriveType() + << " drive type and " << truck.getMileage() + << " miles.\nPrice: $" << truck.getPrice() + << endl << endl; + + cout << "We have the following SUV in inventory:\n" + << suv.getModel() << " " << suv.getMake() + << " with " << suv.getMileage() << " miles and " + << suv.getPassengers() << " passenger capacity.\n" + << "Price: $" << suv.getPrice() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/SUV.h b/SourceCode/chapter 15/Automobile/SUV.h new file mode 100755 index 0000000..76959ca --- /dev/null +++ b/SourceCode/chapter 15/Automobile/SUV.h @@ -0,0 +1,28 @@ +#ifndef SUV_H +#define SUV_H +#include "Automobile.h" +#include +using namespace std; + +// The SUV class represents a SUV. +class SUV : public Automobile +{ +private: + int passengers; + +public: + // Default constructor + SUV() : Automobile() + { passengers = 0; } + + // Constructor #2 + SUV(string SUVMake, int SUVModel, int SUVMileage, + double SUVPrice, int SUVpassengers) : + Automobile(SUVMake, SUVModel, SUVMileage, SUVPrice) + { passengers = SUVpassengers; } + + // Accessor for passengers attribute + int getPassengers() + { return passengers; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Automobile/Truck.h b/SourceCode/chapter 15/Automobile/Truck.h new file mode 100755 index 0000000..0df9ea3 --- /dev/null +++ b/SourceCode/chapter 15/Automobile/Truck.h @@ -0,0 +1,28 @@ +#ifndef TRUCK_H +#define TRUCK_H +#include "Automobile.h" +#include +using namespace std; + +// The Truck class represents a truck. +class Truck : public Automobile +{ +private: + string driveType; + +public: + // Default constructor + Truck() : Automobile() + { driveType = ""; } + + // Constructor #2 + Truck(string truckMake, int truckModel, int truckMileage, + double truckPrice, string truckDriveType) : + Automobile(truckMake, truckModel, truckMileage, truckPrice) + { driveType = truckDriveType; } + + // Accessor for driveType attribute + string getDriveType() + { return driveType; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CsStudent.cpp b/SourceCode/chapter 15/CsStudent.cpp new file mode 100755 index 0000000..40cf067 --- /dev/null +++ b/SourceCode/chapter 15/CsStudent.cpp @@ -0,0 +1,24 @@ +#include +#include "CsStudent.h" +using namespace std; + +//**************************************************** +// The CsStudent::getRemainingHours function returns * +// the number of hours remaining to be taken. * +//**************************************************** + +int CsStudent::getRemainingHours() const +{ + int reqHours, // Total required hours + remainingHours; // Remaining hours + + // Calculate the required hours. + reqHours = MATH_HOURS + CS_HOURS + GEN_ED_HOURS; + + // Calculate the remaining hours. + remainingHours = reqHours - (mathHours + csHours + + genEdHours); + + // Return the remaining hours. + return remainingHours; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/CsStudent.h b/SourceCode/chapter 15/CsStudent.h new file mode 100755 index 0000000..c9168fe --- /dev/null +++ b/SourceCode/chapter 15/CsStudent.h @@ -0,0 +1,46 @@ +// Specification file for the CsStudent class +#ifndef CSSTUDENT_H +#define CSSTUDENT_H +#include "Student.h" + +// Constants for required hours +const int MATH_HOURS = 20; // Math hours +const int CS_HOURS = 40; // Computer science hours +const int GEN_ED_HOURS = 60; // General Ed hours + +class CsStudent : public Student +{ +private: + int mathHours; // Hours of math taken + int csHours; // Hours of Computer Science taken + int genEdHours; // Hours of general education taken + +public: + // Default Constructor + CsStudent() : Student() + { mathHours = 0; + csHours = 0; + genEdHours = 0; } + + // Constructor + CsStudent(string n, string id, int year) : + Student(n, id, year) + { mathHours = 0; + csHours = 0; + genEdHours = 0; } + + // Mutator functions + void setMathHours(int mh) + { mathHours = mh; } + + void setCsHours(int csh) + { csHours = csh; } + + void setGenEdHours(int geh) + { genEdHours = geh; } + + // Overridden getRemainingHours function, + // defined in CsStudent.cpp + virtual int getRemainingHours() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Cube.h b/SourceCode/chapter 15/Cube.h new file mode 100755 index 0000000..b38fe66 --- /dev/null +++ b/SourceCode/chapter 15/Cube.h @@ -0,0 +1,26 @@ +#ifndef CUBE_H +#define CUBE_H +#include "Rectangle.h" + +class Cube : public Rectangle +{ +protected: + double height; + double volume; +public: + // Default constructor + Cube() : Rectangle() + { height = 0.0; volume = 0.0; } + + // Constructor #2 + Cube(double w, double len, double h) : Rectangle(w, len) + { height = h; + volume = getArea() * h; } + + double getHeight() const + { return height; } + + double getVolume() const + { return volume; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/CurvedActivity.h b/SourceCode/chapter 15/CurvedActivity/CurvedActivity.h new file mode 100755 index 0000000..e244d7e --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/CurvedActivity.h @@ -0,0 +1,30 @@ +#ifndef CURVEDACTIVITY_H +#define CURVEDACTIVITY_H +#include "GradedActivity.h" + +class CurvedActivity : public GradedActivity +{ +protected: + double rawScore; // Unadjusted score + double percentage; // Curve percentage +public: + // Default constructor + CurvedActivity() : GradedActivity() + { rawScore = 0.0; percentage = 0.0; } + + // Mutator functions + void setScore(double s) + { rawScore = s; + GradedActivity::setScore(rawScore * percentage); } + + void setPercentage(double c) + { percentage = c; } + + // Accessor funtions + double getPercentage() const + { return percentage; } + + double getRawScore() const + { return rawScore; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/GradedActivity.cpp b/SourceCode/chapter 15/CurvedActivity/GradedActivity.cpp new file mode 100755 index 0000000..c0d9d57 --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/GradedActivity.cpp @@ -0,0 +1,20 @@ +// Implementation file for the GradedActivity class +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::determineGrade * +//****************************************************** + +void GradedActivity::determineGrade() +{ + if (score > 89) + letter = 'A'; + else if (score > 79) + letter = 'B'; + else if (score > 69) + letter = 'C'; + else if (score > 59) + letter = 'D'; + else + letter = 'F'; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/GradedActivity.h b/SourceCode/chapter 15/CurvedActivity/GradedActivity.h new file mode 100755 index 0000000..985c06a --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/GradedActivity.h @@ -0,0 +1,31 @@ +// Specification file for the GradedActivity class +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + char letter; // To hold the letter grade + double score; // To hold the numeric score + void determineGrade(); // Determines the letter grade +public: + // Default constructor + GradedActivity() + { letter = ' '; score = 0.0; } + + // Mutator function + void setScore(double s) + { score = s; + determineGrade();} + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const + { return letter; } +}; + +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/CurvedActivity/Pr15-7.cpp b/SourceCode/chapter 15/CurvedActivity/Pr15-7.cpp new file mode 100755 index 0000000..9ac7ff3 --- /dev/null +++ b/SourceCode/chapter 15/CurvedActivity/Pr15-7.cpp @@ -0,0 +1,38 @@ +// This program demonstrates a class that redefines +// a base class function. +#include +#include +#include "CurvedActivity.h" +using namespace std; + +int main() +{ + double numericScore; // To hold the numeric score + double percentage; // To hold curve percentage + + // Define a CurvedActivity object. + CurvedActivity exam; + + // Get the unadjusted score. + cout << "Enter the student's raw numeric score: "; + cin >> numericScore; + + // Get the curve percentage. + cout << "Enter the curve percentage for this student: "; + cin >> percentage; + + // Send the values to the exam object. + exam.setPercentage(percentage); + exam.setScore(numericScore); + + // Display the grade data. + cout << fixed << setprecision(2); + cout << "The raw score is " + << exam.getRawScore() << endl; + cout << "The curved score is " + << exam.getScore() << endl; + cout << "The curved grade is " + << exam.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Date.h b/SourceCode/chapter 15/Date.h new file mode 100755 index 0000000..6cfb6cb --- /dev/null +++ b/SourceCode/chapter 15/Date.h @@ -0,0 +1,30 @@ +// Specification file for the Date class +#ifndef DATE_H +#define DATE_H + +class Date +{ +protected: + int day; + int month; + int year; +public: + // Default constructor + Date() + { day = 1; month = 1; year = 1900; } + + // Constructor + Date(int d, int m, int y) + { day = d; month = m; year = y; } + + // Accessors + int getDay() const + { return day; } + + int getMonth() const + { return month; } + + int getYear() const + { return year; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/DateTime.cpp b/SourceCode/chapter 15/DateTime.cpp new file mode 100755 index 0000000..10fa86b --- /dev/null +++ b/SourceCode/chapter 15/DateTime.cpp @@ -0,0 +1,35 @@ +// Implementation file for the DateTime class +#include +#include +#include "DateTime.h" +using namespace std; + +//************************************************ +// Default constructor * +// Note that this constructor does nothing other * +// than call default base class constructors. * +//************************************************ +DateTime::DateTime() : Date(), Time() +{ } + +//************************************************ +// Constructor * +// Note that this constructor does nothing other * +// than call base class constructors. * +//************************************************ +DateTime::DateTime(int dy, int mon, int yr, int hr, int mt, int sc) : + Date(dy, mon, yr), Time(hr, mt, sc) +{ } + +//************************************************ +// The showDateTime member function displays the * +// date and the time. * +//************************************************ +void DateTime::showDateTime() const +{ + // Display the date in the form MM/DD/YYYY. + cout << getMonth() << "/" << getDay() << "/" << getYear() << " "; + + // Display the time in the form HH:MM:SS. + cout << getHour() << ":" << getMin() << ":" << getSec() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/DateTime.h b/SourceCode/chapter 15/DateTime.h new file mode 100755 index 0000000..279e241 --- /dev/null +++ b/SourceCode/chapter 15/DateTime.h @@ -0,0 +1,22 @@ +// Specification file for the DateTime class +#ifndef DATETIME_H +#define DATETIME_H +#include +#include "Date.h" +#include "Time.h" +using namespace std; + +class DateTime : public Date, public Time +{ +public: + // Default constructor + DateTime(); + + // Constructor + DateTime(int, int, int, int, int, int); + + // The showDateTime function displays the + // date and the time. + void showDateTime() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.cpp b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.cpp new file mode 100755 index 0000000..44a69d5 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.cpp @@ -0,0 +1,26 @@ +#include "FinalExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void FinalExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.h b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.h new file mode 100755 index 0000000..db1fe72 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/FinalExam.h @@ -0,0 +1,35 @@ +#ifndef FINALEXAM_H +#define FINALEXAM_H +#include "GradedActivity.h" + +class FinalExam : public GradedActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + FinalExam() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + FinalExam(int questions, int missed) + { set(questions, missed); } + + // Mutator function + void set(int, int); // Defined in FinalExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.h b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.h new file mode 100755 index 0000000..b214f73 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +private: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/Pr15-1.cpp b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-1.cpp new file mode 100755 index 0000000..9bee58a --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-1.cpp @@ -0,0 +1,25 @@ +// This program demonstrates the GradedActivity class. +#include +#include "GradedActivity.h" +using namespace std; + +int main() +{ + double testScore; // To hold a test score + + // Create a GradedActivity object for the test. + GradedActivity test; + + // Get a numeric test score from the user. + cout << "Enter your numeric test score: "; + cin >> testScore; + + // Store the numeric score in the test object. + test.setScore(testScore); + + // Display the letter grade for the test. + cout << "The grade for that test is " + << test.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 1/Pr15-2.cpp b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-2.cpp new file mode 100755 index 0000000..792d1fe --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 1/Pr15-2.cpp @@ -0,0 +1,32 @@ +// This program demonstrates a base class and a derived class. +#include +#include +#include "FinalExam.h" +using namespace std; + +int main() +{ + int questions; // Number of questions on the exam + int missed; // Number of questions missed by the student + + // Get the number of questions on the final exam. + cout << "How many questions are on the final exam? "; + cin >> questions; + + // Get the number of questions the student missed. + cout << "How many questions did the student miss? "; + cin >> missed; + + // Define a FinalExam object and initialize it with + // the values entered. + FinalExam test(questions, missed); + + // Display the test results. + cout << setprecision(2); + cout << "\nEach question counts " << test.getPointsEach() + << " points.\n"; + cout << "The exam score is " << test.getScore() << endl; + cout << "The exam grade is " << test.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.cpp b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.cpp new file mode 100755 index 0000000..7970daf --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.cpp @@ -0,0 +1,47 @@ +#include "FinalExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void FinalExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); + + // Call the adjustScore function to adjust + // the score. + adjustScore(); +} + +//***************************************************************** +// Definition of Test::adjustScore. If score is within 0.5 points * +// of the next whole point, it rounds the score up and * +// recalculates the letter grade. * +//***************************************************************** + +void FinalExam::adjustScore() +{ + double fraction = score - static_cast(score); + + if (fraction >= 0.5) + { + // Adjust the score variable in the GradedActivity class. + score += (1.0 - fraction); + } +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.h b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.h new file mode 100755 index 0000000..370ef7b --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/FinalExam.h @@ -0,0 +1,36 @@ +#ifndef FINALEXAM_H +#define FINALEXAM_H +#include "GradedActivity.h" + +class FinalExam : public GradedActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + FinalExam() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + FinalExam(int questions, int missed) + { set(questions, missed); } + + // Mutator functions + void set(int, int); // Defined in FinalExam.cpp + void adjustScore(); // Defined in FinalExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.h b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.h new file mode 100755 index 0000000..9233cf8 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 2/Pr15-3.cpp b/SourceCode/chapter 15/GradedActivity Version 2/Pr15-3.cpp new file mode 100755 index 0000000..11dc1ad --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 2/Pr15-3.cpp @@ -0,0 +1,35 @@ +// This program demonstrates a base class with a +// protected member. +#include +#include +#include "FinalExam.h" +using namespace std; + +int main() +{ + int questions; // Number of questions on the exam + int missed; // Number of questions missed by the student + + // Get the number of questions on the final exam. + cout << "How many questions are on the final exam? "; + cin >> questions; + + // Get the number of questions the student missed. + cout << "How many questions did the student miss? "; + cin >> missed; + + // Define a FinalExam object and initialize it with + // the values entered. + FinalExam test(questions, missed); + + // Display the adjusted test results. + cout << setprecision(2) << fixed; + cout << "\nEach question counts " + << test.getPointsEach() << " points.\n"; + cout << "The adjusted exam score is " + << test.getScore() << endl; + cout << "The exam grade is " + << test.getLetterGrade() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.h b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.h new file mode 100755 index 0000000..8aef331 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + virtual char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.cpp b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.cpp new file mode 100755 index 0000000..30b26b1 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.cpp @@ -0,0 +1,19 @@ +#include "PassFailActivity.h" + +//****************************************************** +// Member function PassFailActivity::getLetterGrade * +// This function returns 'P' if the score is passing, * +// otherwise it returns 'F'. * +//****************************************************** + +char PassFailActivity::getLetterGrade() const +{ + char letterGrade; + + if (score >= minPassingScore) + letterGrade = 'P'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h new file mode 100755 index 0000000..a0e5822 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailActivity.h @@ -0,0 +1,28 @@ +#ifndef PASSFAILACTIVITY_H +#define PASSFAILACTIVITY_H +#include "GradedActivity.h" + +class PassFailActivity : public GradedActivity +{ +protected: + double minPassingScore; // Minimum passing score. +public: + // Default constructor + PassFailActivity() : GradedActivity() + { minPassingScore = 0.0; } + + // Constructor + PassFailActivity(double mps) : GradedActivity() + { minPassingScore = mps; } + + // Mutator + void setMinPassingScore(double mps) + { minPassingScore = mps; } + + // Accessors + double getMinPassingScore() const + { return minPassingScore; } + + virtual char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.cpp b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.cpp new file mode 100755 index 0000000..37e6059 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.cpp @@ -0,0 +1,26 @@ +#include "PassFailExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void PassFailExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h new file mode 100755 index 0000000..6cddc78 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/PassFailExam.h @@ -0,0 +1,36 @@ +#ifndef PASSFAILEXAM_H +#define PASSFAILEXAM_H +#include "PassFailActivity.h" + +class PassFailExam : public PassFailActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + PassFailExam() : PassFailActivity() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + PassFailExam(int questions, int missed, double mps) : + PassFailActivity(mps) + { set(questions, missed); } + + // Mutator function + void set(int, int); // Defined in PassFailExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-11.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-11.cpp new file mode 100755 index 0000000..a7e2ff5 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-11.cpp @@ -0,0 +1,36 @@ +#include +#include +#include "PassFailActivity.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity &); + +int main() +{ + // Create a PassFailActivity object. Minimum passing + // score is 70. + PassFailActivity test(70); + + // Set the score to 72. + test.setScore(72); + + // Display the object's grade data. The letter grade + // should be 'P'. What will be displayed? + displayGrade(test); + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. * +//*************************************************************** + +void displayGrade(const GradedActivity &activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity.getScore() << endl; + cout << "The activity's letter grade is " + << activity.getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-12.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-12.cpp new file mode 100755 index 0000000..3e4d539 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-12.cpp @@ -0,0 +1,39 @@ +#include +#include +#include "PassFailExam.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity &); + +int main() +{ + // Create a GradedActivity object. The score is 88. + GradedActivity test1(88.0); + + // Create a PassFailExam object. There are 100 questions, + // the student missed 25 of them, and the minimum passing + // score is 70. + PassFailExam test2(100, 25, 70.0); + + // Display the grade data for both objects. + cout << "Test 1:\n"; + displayGrade(test1); // GradedActivity object + cout << "\nTest 2:\n"; + displayGrade(test2); // PassFailExam object + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. * +//*************************************************************** + +void displayGrade(const GradedActivity &activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity.getScore() << endl; + cout << "The activity's letter grade is " + << activity.getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-13.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-13.cpp new file mode 100755 index 0000000..8bf77b4 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-13.cpp @@ -0,0 +1,40 @@ +#include +#include +#include "PassFailExam.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity *); + +int main() +{ + // Create a GradedActivity object. The score is 88. + GradedActivity test1(88.0); + + // Create a PassFailExam object. There are 100 questions, + // the student missed 25 of them, and the minimum passing + // score is 70. + PassFailExam test2(100, 25, 70.0); + + // Display the grade data for both objects. + cout << "Test 1:\n"; + displayGrade(&test1); // Address of the GradedActivity object + cout << "\nTest 2:\n"; + displayGrade(&test2); // Address of the PassFailExam object + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. This version of the function * +// uses a GradedActivity pointer as its parameter. * +//*************************************************************** + +void displayGrade(const GradedActivity *activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity->getScore() << endl; + cout << "The activity's letter grade is " + << activity->getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/GradedActivity Version 3/Pr15-14.cpp b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-14.cpp new file mode 100755 index 0000000..f066711 --- /dev/null +++ b/SourceCode/chapter 15/GradedActivity Version 3/Pr15-14.cpp @@ -0,0 +1,47 @@ +#include +#include +#include "PassFailExam.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity *); + +int main() +{ + // Constant for the size of an array. + const int NUM_TESTS = 4; + + // tests is an array of GradedActivity pointers. + // Each element of tests is initialized with the + // address of a dynamically allocated object. + GradedActivity *tests[NUM_TESTS] = + { new GradedActivity(88.0), + new PassFailExam(100, 25, 70.0), + new GradedActivity(67.0), + new PassFailExam(50, 12, 60.0) + }; + + // Display the grade data for each element in the array. + for (int count = 0; count < NUM_TESTS; count++) + { + cout << "Test #" << (count + 1) << ":\n"; + displayGrade(tests[count]); + cout << endl; + } + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. This version of the function * +// uses a GradedActivity pointer as its parameter. * +//*************************************************************** + +void displayGrade(const GradedActivity *activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity->getScore() << endl; + cout << "The activity's letter grade is " + << activity->getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/GradedActivity.cpp b/SourceCode/chapter 15/PassFailActivity/GradedActivity.cpp new file mode 100755 index 0000000..ce6216e --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/GradedActivity.cpp @@ -0,0 +1,23 @@ +#include "GradedActivity.h" + +//****************************************************** +// Member function GradedActivity::getLetterGrade * +//****************************************************** + +char GradedActivity::getLetterGrade() const +{ + char letterGrade; // To hold the letter grade + + if (score > 89) + letterGrade = 'A'; + else if (score > 79) + letterGrade = 'B'; + else if (score > 69) + letterGrade = 'C'; + else if (score > 59) + letterGrade = 'D'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/GradedActivity.h b/SourceCode/chapter 15/PassFailActivity/GradedActivity.h new file mode 100755 index 0000000..9233cf8 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/GradedActivity.h @@ -0,0 +1,29 @@ +#ifndef GRADEDACTIVITY_H +#define GRADEDACTIVITY_H + +// GradedActivity class declaration + +class GradedActivity +{ +protected: + double score; // To hold the numeric score +public: + // Default constructor + GradedActivity() + { score = 0.0; } + + // Constructor + GradedActivity(double s) + { score = s; } + + // Mutator function + void setScore(double s) + { score = s; } + + // Accessor functions + double getScore() const + { return score; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp new file mode 100755 index 0000000..30b26b1 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.cpp @@ -0,0 +1,19 @@ +#include "PassFailActivity.h" + +//****************************************************** +// Member function PassFailActivity::getLetterGrade * +// This function returns 'P' if the score is passing, * +// otherwise it returns 'F'. * +//****************************************************** + +char PassFailActivity::getLetterGrade() const +{ + char letterGrade; + + if (score >= minPassingScore) + letterGrade = 'P'; + else + letterGrade = 'F'; + + return letterGrade; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailActivity.h b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.h new file mode 100755 index 0000000..becadcc --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailActivity.h @@ -0,0 +1,28 @@ +#ifndef PASSFAILACTIVITY_H +#define PASSFAILACTIVITY_H +#include "GradedActivity.h" + +class PassFailActivity : public GradedActivity +{ +protected: + double minPassingScore; // Minimum passing score. +public: + // Default constructor + PassFailActivity() : GradedActivity() + { minPassingScore = 0.0; } + + // Constructor + PassFailActivity(double mps) : GradedActivity() + { minPassingScore = mps; } + + // Mutator + void setMinPassingScore(double mps) + { minPassingScore = mps; } + + // Accessors + double getMinPassingScore() const + { return minPassingScore; } + + char getLetterGrade() const; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp b/SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp new file mode 100755 index 0000000..37e6059 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailExam.cpp @@ -0,0 +1,26 @@ +#include "PassFailExam.h" + +//******************************************************** +// set function * +// The parameters are the number of questions and the * +// number of questions missed. * +//******************************************************** + +void PassFailExam::set(int questions, int missed) +{ + double numericScore; // To hold the numeric score + + // Set the number of questions and number missed. + numQuestions = questions; + numMissed = missed; + + // Calculate the points for each question. + pointsEach = 100.0 / numQuestions; + + // Calculate the numeric score for this exam. + numericScore = 100.0 - (missed * pointsEach); + + // Call the inherited setScore function to set + // the numeric score. + setScore(numericScore); +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/PassFailExam.h b/SourceCode/chapter 15/PassFailActivity/PassFailExam.h new file mode 100755 index 0000000..6cddc78 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/PassFailExam.h @@ -0,0 +1,36 @@ +#ifndef PASSFAILEXAM_H +#define PASSFAILEXAM_H +#include "PassFailActivity.h" + +class PassFailExam : public PassFailActivity +{ +private: + int numQuestions; // Number of questions + double pointsEach; // Points for each question + int numMissed; // Number of questions missed +public: + // Default constructor + PassFailExam() : PassFailActivity() + { numQuestions = 0; + pointsEach = 0.0; + numMissed = 0; } + + // Constructor + PassFailExam(int questions, int missed, double mps) : + PassFailActivity(mps) + { set(questions, missed); } + + // Mutator function + void set(int, int); // Defined in PassFailExam.cpp + + // Accessor functions + double getNumQuestions() const + { return numQuestions; } + + double getPointsEach() const + { return pointsEach; } + + int getNumMissed() const + { return numMissed; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/Pr15-10.cpp b/SourceCode/chapter 15/PassFailActivity/Pr15-10.cpp new file mode 100755 index 0000000..a7e2ff5 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/Pr15-10.cpp @@ -0,0 +1,36 @@ +#include +#include +#include "PassFailActivity.h" +using namespace std; + +// Function prototype +void displayGrade(const GradedActivity &); + +int main() +{ + // Create a PassFailActivity object. Minimum passing + // score is 70. + PassFailActivity test(70); + + // Set the score to 72. + test.setScore(72); + + // Display the object's grade data. The letter grade + // should be 'P'. What will be displayed? + displayGrade(test); + return 0; +} + +//*************************************************************** +// The displayGrade function displays a GradedActivity object's * +// numeric score and letter grade. * +//*************************************************************** + +void displayGrade(const GradedActivity &activity) +{ + cout << setprecision(1) << fixed; + cout << "The activity's numeric score is " + << activity.getScore() << endl; + cout << "The activity's letter grade is " + << activity.getLetterGrade() << endl; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/PassFailActivity/Pr15-9.cpp b/SourceCode/chapter 15/PassFailActivity/Pr15-9.cpp new file mode 100755 index 0000000..273d261 --- /dev/null +++ b/SourceCode/chapter 15/PassFailActivity/Pr15-9.cpp @@ -0,0 +1,39 @@ +// This program demonstrates the PassFailExam class. +#include +#include +#include "PassFailExam.h" +using namespace std; + +int main() +{ + int questions; // Number of questions + int missed; // Number of questions missed + double minPassing; // The minimum passing score + + // Get the number of questions on the exam. + cout << "How many questions are on the exam? "; + cin >> questions; + + // Get the number of questions the student missed. + cout << "How many questions did the student miss? "; + cin >> missed; + + // Get the minimum passing score. + cout << "Enter the minimum passing score for this test: "; + cin >> minPassing; + + // Define a PassFailExam object. + PassFailExam exam(questions, missed, minPassing); + + // Display the test results. + cout << fixed << setprecision(1); + cout << "\nEach question counts " + << exam.getPointsEach() << " points.\n"; + cout << "The minimum passing score is " + << exam.getMinPassingScore() << endl; + cout << "The student's exam score is " + << exam.getScore() << endl; + cout << "The student's grade is " + << exam.getLetterGrade() << endl; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-15.cpp b/SourceCode/chapter 15/Pr15-15.cpp new file mode 100755 index 0000000..2edeb35 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-15.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +// Animal is a base class. +class Animal +{ +public: + // Constructor + Animal() + { cout << "Animal constructor executing.\n"; } + + // Destructor + ~Animal() + { cout << "Animal destructor executing.\n"; } +}; + +// The Dog class is derived from Animal +class Dog : public Animal +{ +public: + // Constructor + Dog() : Animal() + { cout << "Dog constructor executing.\n"; } + + // Destructor + ~Dog() + { cout << "Dog destructor executing.\n"; } +}; + +//************************************************* +// main function * +//************************************************* + +int main() +{ + // Create a Dog object, referenced by an + // Animal pointer. + Animal *myAnimal = new Dog; + + // Delete the dog object. + delete myAnimal; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-16.cpp b/SourceCode/chapter 15/Pr15-16.cpp new file mode 100755 index 0000000..408fc7d --- /dev/null +++ b/SourceCode/chapter 15/Pr15-16.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +// Animal is a base class. +class Animal +{ +public: + // Constructor + Animal() + { cout << "Animal constructor executing.\n"; } + + // Destructor + virtual ~Animal() + { cout << "Animal destructor executing.\n"; } +}; + +// The Dog class is derived from Animal +class Dog : public Animal +{ +public: + // Constructor + Dog() : Animal() + { cout << "Dog constructor executing.\n"; } + + // Destructor + ~Dog() + { cout << "Dog destructor executing.\n"; } +}; + +//************************************************* +// main function * +//************************************************* + +int main() +{ + // Create a Dog object, referenced by an + // Animal pointer. + Animal *myAnimal = new Dog; + + // Delete the dog object. + delete myAnimal; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-17.cpp b/SourceCode/chapter 15/Pr15-17.cpp new file mode 100755 index 0000000..0b95fcc --- /dev/null +++ b/SourceCode/chapter 15/Pr15-17.cpp @@ -0,0 +1,30 @@ +// This program has a subtle error in the virtual functions. +#include +using namespace std; + +class Base +{ +public: + virtual void functionA(int arg) const + { cout << "This is Base::functionA" << endl; } +}; + +class Derived : public Base +{ +public: + virtual void functionA(long arg) const + { cout << "This is Derived::functionA" << endl; } +}; + +int main() +{ + // Allocate instances of the Derived class. + Base *b = new Derived(); + Derived *d = new Derived(); + + // Call functionA with the two pointers. + b->functionA(99); + d->functionA(99); + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-18.cpp b/SourceCode/chapter 15/Pr15-18.cpp new file mode 100755 index 0000000..cf9f0f7 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-18.cpp @@ -0,0 +1,30 @@ +// This program demonstrates the override key word. +#include +using namespace std; + +class Base +{ +public: + virtual void functionA(int arg) const + { cout << "This is Base::functionA" << endl; } +}; + +class Derived : public Base +{ +public: + virtual void functionA(int arg) const override + { cout << "This is Derived::functionA" << endl; } +}; + +int main() +{ + // Allocate instances of the Derived class. + Base *b = new Derived(); + Derived *d = new Derived(); + + // Call functionA with the two pointers. + b->functionA(99); + d->functionA(99); + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-19.cpp b/SourceCode/chapter 15/Pr15-19.cpp new file mode 100755 index 0000000..c6f868d --- /dev/null +++ b/SourceCode/chapter 15/Pr15-19.cpp @@ -0,0 +1,24 @@ +// This program demonstrates the CsStudent class, which is +// derived from the abstract base class, Student. +#include +#include "CsStudent.h" +using namespace std; + +int main() +{ + // Create a CsStudent object for a student. + CsStudent student("Jennifer Haynes", "167W98337", 2006); + + // Store values for Math, Computer Science, and General + // Ed hours. + student.setMathHours(12); // Student has taken 12 Math hours + student.setCsHours(20); // Studeht has taken 20 CS hours + student.setGenEdHours(40); // Student has taken 40 Gen Ed hours + + // Display the number of remaining hours. + cout << "The student " << student.getName() + << " needs to take " << student.getRemainingHours() + << " more hours to graduate.\n"; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-20.cpp b/SourceCode/chapter 15/Pr15-20.cpp new file mode 100755 index 0000000..7efba25 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-20.cpp @@ -0,0 +1,21 @@ +// This program demonstrates a class with multiple inheritance. +#include "DateTime.h" +using namespace std; + +int main() +{ + // Define a DateTime object and use the default + // constructor to initialize it. + DateTime emptyDay; + + // Display the object's date and time. + emptyDay.showDateTime(); + + // Define a DateTime object and initialize it + // with the date 2/4/1960 and the time 5:32:27. + DateTime pastDay(2, 4, 1960, 5, 32, 27); + + // Display the object's date and time. + pastDay.showDateTime(); + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-4.cpp b/SourceCode/chapter 15/Pr15-4.cpp new file mode 100755 index 0000000..b0979fe --- /dev/null +++ b/SourceCode/chapter 15/Pr15-4.cpp @@ -0,0 +1,46 @@ +// This program demonstrates the order in which base and +// derived class constructors and destructors are called. +#include +using namespace std; + +//******************************** +// BaseClass declaration * +//******************************** + +class BaseClass +{ +public: + BaseClass() // Constructor + { cout << "This is the BaseClass constructor.\n"; } + + ~BaseClass() // Destructor + { cout << "This is the BaseClass destructor.\n"; } +}; + +//******************************** +// DerivedClass declaration * +//******************************** + +class DerivedClass : public BaseClass +{ +public: + DerivedClass() // Constructor + { cout << "This is the DerivedClass constructor.\n"; } + + ~DerivedClass() // Destructor + { cout << "This is the DerivedClass destructor.\n"; } +}; + +//******************************** +// main function * +//******************************** + +int main() +{ + cout << "We will now define a DerivedClass object.\n"; + + DerivedClass object; + + cout << "The program is now going to end.\n"; + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-5.cpp b/SourceCode/chapter 15/Pr15-5.cpp new file mode 100755 index 0000000..62f9986 --- /dev/null +++ b/SourceCode/chapter 15/Pr15-5.cpp @@ -0,0 +1,36 @@ +// This program demonstrates passing arguments to a base +// class constructor. +#include +#include "Cube.h" +using namespace std; + +int main() +{ + double cubeWidth; // To hold the cube's width + double cubeLength; // To hold the cube's length + double cubeHeight; // To hold the cube's height + + // Get the width, length, and height of + // the cube from the user. + cout << "Enter the dimensions of a Cube:\n"; + cout << "Width: "; + cin >> cubeWidth; + cout << "Length: "; + cin >> cubeLength; + cout << "Height: "; + cin >> cubeHeight; + + // Define a Cube object and use the dimensions + // entered by the user. + Cube myCube(cubeWidth, cubeLength, cubeHeight); + + // Display the Cube object's properties. + cout << "Here are the Cube's properties:\n"; + cout << "Width: " << myCube.getWidth() << endl; + cout << "Length: " << myCube.getLength() << endl; + cout << "Height: " << myCube.getHeight() << endl; + cout << "Base area: " << myCube.getArea() << endl; + cout << "Volume: " << myCube.getVolume() << endl; + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Pr15-8.cpp b/SourceCode/chapter 15/Pr15-8.cpp new file mode 100755 index 0000000..041383d --- /dev/null +++ b/SourceCode/chapter 15/Pr15-8.cpp @@ -0,0 +1,30 @@ +// This program demonstrates that when a derived class function +// overrides a base class function, objects of the base class +// still call the base class version of the function. +#include +using namespace std; + +class BaseClass +{ +public: + void showMessage() + { cout << "This is the Base class.\n"; } +}; + +class DerivedClass : public BaseClass +{ +public: + void showMessage() + { cout << "This is the Derived class.\n"; } +}; + +int main() +{ + BaseClass b; + DerivedClass d; + + b.showMessage(); + d.showMessage(); + + return 0; +} \ No newline at end of file diff --git a/SourceCode/chapter 15/Rectangle.h b/SourceCode/chapter 15/Rectangle.h new file mode 100755 index 0000000..709561a --- /dev/null +++ b/SourceCode/chapter 15/Rectangle.h @@ -0,0 +1,29 @@ +#ifndef RECTANGLE_H +#define RECTANGLE_H + +class Rectangle +{ +private: + double width; + double length; +public: + // Default constructor + Rectangle() + { width = 0.0; + length = 0.0; } + + // Constructor #2 + Rectangle(double w, double len) + { width = w; + length = len; } + + double getWidth() const + { return width; } + + double getLength() const + { return length; } + + double getArea() const + { return width * length; } +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Student.h b/SourceCode/chapter 15/Student.h new file mode 100755 index 0000000..07c72d9 --- /dev/null +++ b/SourceCode/chapter 15/Student.h @@ -0,0 +1,43 @@ +// Specification file for the Student class +#ifndef STUDENT_H +#define STUDENT_H +#include +using namespace std; + +class Student +{ +protected: + string name; // Student name + string idNumber; // Student ID + int yearAdmitted; // Year student was admitted +public: + // Default constructor + Student() + { name = ""; + idNumber = ""; + yearAdmitted = 0; } + + // Constructor + Student(string n, string id, int year) + { set(n, id, year); } + + // The set function sets the attribute data. + void set(string n, string id, int year) + { name = n; // Assign the name + idNumber = id; // Assign the ID number + yearAdmitted = year; } // Assign year admitted + + // Accessor functions + const string getName() const + { return name; } + + const string getIdNum() const + { return idNumber; } + + int getYearAdmitted() const + { return yearAdmitted; } + + // Pure virtual function + virtual int getRemainingHours() const = 0; +}; +#endif \ No newline at end of file diff --git a/SourceCode/chapter 15/Time.h b/SourceCode/chapter 15/Time.h new file mode 100755 index 0000000..8941d08 --- /dev/null +++ b/SourceCode/chapter 15/Time.h @@ -0,0 +1,30 @@ +// Specification file for the Time class +#ifndef TIME_H +#define TIME_H + +class Time +{ +protected: + int hour; + int min; + int sec; +public: + // Default constructor + Time() + { hour = 0; min = 0; sec = 0; } + + // Constructor + Time(int h, int m, int s) + { hour = h; min = m; sec = s; } + + // Accessor functions + int getHour() const + { return hour; } + + int getMin() const + { return min; } + + int getSec() const + { return sec; } +}; +#endif \ No newline at end of file