Presentation is loading. Please wait.

Presentation is loading. Please wait.

////////////////////////////////////////////////////// // This program retrieves dimensional box data from // // a user-specified input file and determines.

Similar presentations


Presentation on theme: "////////////////////////////////////////////////////// // This program retrieves dimensional box data from // // a user-specified input file and determines."— Presentation transcript:

1

2

3 ////////////////////////////////////////////////////// // This program retrieves dimensional box data from // // a user-specified input file and determines the // // maximum volume and the maximum surface area for // // all boxes with dimensions listed in the file. // ////////////////////////////////////////////////////// #include using namespace std; double volume(double length, double width, double height); double surfaceArea(double length, double width, double height); // The main function queries the user for the input // // file name, opens the file, coordinates the retrieval // // of the dimensional data, and outputs the resulting // // maxima for volumes and surface areas. // void main() { string boxDataFileName; ifstream boxDataFile; double dim1, dim2, dim3; double largestVolume = -1.0; double largestSurfaceArea = -1.0; double newVolume; double newSurfaceArea; ////////////////////////////////////////////////////// // This program retrieves dimensional box data from // // a user-specified input file and determines the // // maximum volume and the maximum surface area for // // all boxes with dimensions listed in the file. // ////////////////////////////////////////////////////// #include using namespace std; double volume(double length, double width, double height); double surfaceArea(double length, double width, double height); // The main function queries the user for the input // // file name, opens the file, coordinates the retrieval // // of the dimensional data, and outputs the resulting // // maxima for volumes and surface areas. // void main() { string boxDataFileName; ifstream boxDataFile; double dim1, dim2, dim3; double largestVolume = -1.0; double largestSurfaceArea = -1.0; double newVolume; double newSurfaceArea;

4 cout << "EXTREME BOX CALCULATOR" << endl << " " << endl; cout << "Enter the name of the file" << endl << "containing box dimension data: "; cin >> boxDataFileName; boxDataFile.open(boxDataFileName.c_str()); while (boxDataFile.fail()) { cout << endl << "NO FILE WITH THAT NAME LOCATED." << endl << "PLEASE TRY AGAIN WITH AN EXISTING FILE.” << endl << endl; cout << "Enter the name of the file" << endl << "containing box dimension data: "; cin >> boxDataFileName; boxDataFile.open(boxDataFileName.c_str()); } boxDataFile >> dim1; while (!boxDataFile.eof()) { boxDataFile >> dim2 >> dim3; newVolume = volume(dim1, dim2, dim3); if (newVolume > largestVolume) largestVolume = newVolume; newSurfaceArea = surfaceArea(dim1, dim2, dim3); if (newSurfaceArea > largestSurfaceArea) largestSurfaceArea = newSurfaceArea; boxDataFile >> dim1; } if ((newVolume < 0.0) || (newSurfaceArea < 0.0)) cout << endl << "NO LEGITIMATE BOX DIMENSIONS FOUND IN FILE"; else cout << endl << "Largest Box Volume: " << int(largestVolume) << " cubic units" << endl << "Largest Box Surface Area: " << int(largestSurfaceArea) << " square units"; cout << endl << endl; return; } cout << "EXTREME BOX CALCULATOR" << endl << " " << endl; cout << "Enter the name of the file" << endl << "containing box dimension data: "; cin >> boxDataFileName; boxDataFile.open(boxDataFileName.c_str()); while (boxDataFile.fail()) { cout << endl << "NO FILE WITH THAT NAME LOCATED." << endl << "PLEASE TRY AGAIN WITH AN EXISTING FILE.” << endl << endl; cout << "Enter the name of the file" << endl << "containing box dimension data: "; cin >> boxDataFileName; boxDataFile.open(boxDataFileName.c_str()); } boxDataFile >> dim1; while (!boxDataFile.eof()) { boxDataFile >> dim2 >> dim3; newVolume = volume(dim1, dim2, dim3); if (newVolume > largestVolume) largestVolume = newVolume; newSurfaceArea = surfaceArea(dim1, dim2, dim3); if (newSurfaceArea > largestSurfaceArea) largestSurfaceArea = newSurfaceArea; boxDataFile >> dim1; } if ((newVolume < 0.0) || (newSurfaceArea < 0.0)) cout << endl << "NO LEGITIMATE BOX DIMENSIONS FOUND IN FILE"; else cout << endl << "Largest Box Volume: " << int(largestVolume) << " cubic units" << endl << "Largest Box Surface Area: " << int(largestSurfaceArea) << " square units"; cout << endl << endl; return; }

5 // The volume function calculates and returns the volume of the // // box with the parameterized dimensions. It returns an invalid // // value if any dimension is determined to be invalid. // double volume(double length, double width, double height) { if ((length >= 0.0) && (width >= 0.0) && (height >= 0.0)) return (length * width * height); else return -1.0; } // The surfaceArea function calculates and returns the surface // // of the box with the parameterized dimensions. It returns an // // invalid value if any dimension is determined to be invalid. // double surfaceArea(double length, double width, double height) { double frontArea = length * height; double sideArea = width * height; double topArea = length * width; if ((length >= 0.0) && (width >= 0.0) && (height >= 0.0)) return (2 * frontArea + 2 * sideArea + 2 * topArea); else return -1.0; } // The volume function calculates and returns the volume of the // // box with the parameterized dimensions. It returns an invalid // // value if any dimension is determined to be invalid. // double volume(double length, double width, double height) { if ((length >= 0.0) && (width >= 0.0) && (height >= 0.0)) return (length * width * height); else return -1.0; } // The surfaceArea function calculates and returns the surface // // of the box with the parameterized dimensions. It returns an // // invalid value if any dimension is determined to be invalid. // double surfaceArea(double length, double width, double height) { double frontArea = length * height; double sideArea = width * height; double topArea = length * width; if ((length >= 0.0) && (width >= 0.0) && (height >= 0.0)) return (2 * frontArea + 2 * sideArea + 2 * topArea); else return -1.0; }

6 ////////////////////////////////////////////// // This program computes the value to which // // a power series converges, and the number // // of iterations required before the series // // can be said to converge. // ////////////////////////////////////////////// #include using namespace std; double queryUserForValue(); void computeSeries(double x, double &sum, int &nbrLoops); void outputResults(double result, int iterations); // The main function coordinates the retrieval // // of the value to be used in the power series, // // the calculation of the series limit, and the // // output of the results. // void main() { double number, convergentValue; int nbrIterations; number = queryUserForValue(); computeSeries(number, convergentValue, nbrIterations); outputResults(convergentValue, nbrIterations); } ////////////////////////////////////////////// // This program computes the value to which // // a power series converges, and the number // // of iterations required before the series // // can be said to converge. // ////////////////////////////////////////////// #include using namespace std; double queryUserForValue(); void computeSeries(double x, double &sum, int &nbrLoops); void outputResults(double result, int iterations); // The main function coordinates the retrieval // // of the value to be used in the power series, // // the calculation of the series limit, and the // // output of the results. // void main() { double number, convergentValue; int nbrIterations; number = queryUserForValue(); computeSeries(number, convergentValue, nbrIterations); outputResults(convergentValue, nbrIterations); }

7 // This function queries the user for the // // power series generator value, which must // // be strictly between 0 and 1. // double queryUserForValue() { double nbr; cout << "Enter the number to be tested: "; cin >> nbr; while ((nbr = 1.0)) { cout << "The number must be greater than 0 and less than 1." << endl << "Enter the number to be tested: "; cin >> nbr; } return nbr; } // This function repeatedly adds the next power // // of the generator value to the series expansion, // // until two consecutive sums are equal, at which // // time the series is considered to converge. // void computeSeries(double x, double &sum, int &nbrLoops) { double powerOfX, previousSum = 0.0; nbrLoops = 0; sum = x; powerOfX = x; while (previousSum < sum) { nbrLoops++; previousSum = sum; powerOfX *= x; sum += powerOfX; } // This function queries the user for the // // power series generator value, which must // // be strictly between 0 and 1. // double queryUserForValue() { double nbr; cout << "Enter the number to be tested: "; cin >> nbr; while ((nbr = 1.0)) { cout << "The number must be greater than 0 and less than 1." << endl << "Enter the number to be tested: "; cin >> nbr; } return nbr; } // This function repeatedly adds the next power // // of the generator value to the series expansion, // // until two consecutive sums are equal, at which // // time the series is considered to converge. // void computeSeries(double x, double &sum, int &nbrLoops) { double powerOfX, previousSum = 0.0; nbrLoops = 0; sum = x; powerOfX = x; while (previousSum < sum) { nbrLoops++; previousSum = sum; powerOfX *= x; sum += powerOfX; }

8 // This function outputs the power series // // final value, as well as the number of // // iterations required to obtain it. // void outputResults(double result, int iterations) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(8); cout << "The series converges to " << result << " in " << iterations << " iterations." << endl << endl; } // This function outputs the power series // // final value, as well as the number of // // iterations required to obtain it. // void outputResults(double result, int iterations) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(8); cout << "The series converges to " << result << " in " << iterations << " iterations." << endl << endl; }

9 //////////////////////////////////////////////////////////////// // This program queries the user for the coefficients of a // // cubic polynomial and then uses ASCII characters to graph // // the polynomial in a user-specified range of the x-y plane. // //////////////////////////////////////////////////////////////// #include using namespace std; void queryUserForCoefficients(double &coeff3, double &coeff2, double &coeff1, double &coeff0); double queryUserForCoefficient(int exponent); void queryUserForRange(char axisLabel, int &rangeMin, int &rangeMax); void graphCubic(int xMin, int xMax, int yMin, int yMax, double coeff3, double coeff2, double coeff1, double coeff0); void outputLabel(double coeff3, double coeff2, double coeff1, double coeff0); void outputCubicTerm(double coeff3); void outputQuadraticTerm(double coeff3, double coeff2); void outputLinearTerm(double coeff3, double coeff2, double coeff1); void outputConstantTerm(double coeff3, double coeff2, double coeff1, double coeff0); void outputStrip(int yVal, int xMin, int xMax, double coeff3, double coeff2, double coeff1, double coeff0); bool closePoint(int xVal, int yVal, double coeff3, double coeff2, double coeff1, double coeff0); //////////////////////////////////////////////////////////////// // This program queries the user for the coefficients of a // // cubic polynomial and then uses ASCII characters to graph // // the polynomial in a user-specified range of the x-y plane. // //////////////////////////////////////////////////////////////// #include using namespace std; void queryUserForCoefficients(double &coeff3, double &coeff2, double &coeff1, double &coeff0); double queryUserForCoefficient(int exponent); void queryUserForRange(char axisLabel, int &rangeMin, int &rangeMax); void graphCubic(int xMin, int xMax, int yMin, int yMax, double coeff3, double coeff2, double coeff1, double coeff0); void outputLabel(double coeff3, double coeff2, double coeff1, double coeff0); void outputCubicTerm(double coeff3); void outputQuadraticTerm(double coeff3, double coeff2); void outputLinearTerm(double coeff3, double coeff2, double coeff1); void outputConstantTerm(double coeff3, double coeff2, double coeff1, double coeff0); void outputStrip(int yVal, int xMin, int xMax, double coeff3, double coeff2, double coeff1, double coeff0); bool closePoint(int xVal, int yVal, double coeff3, double coeff2, double coeff1, double coeff0);

10 // The main function supervises querying the user for the // // cubic's coefficients and the range to be used within the // // x-y plane, as well as the actual graphing of the cubic. // void main() { double cubicCoeff, quadraticCoeff, linearCoeff, constantCoeff; int minXValue, maxXValue, minYValue, maxYValue; queryUserForCoefficients(cubicCoeff, quadraticCoeff, linearCoeff, constantCoeff); queryUserForRange('x', minXValue, maxXValue); queryUserForRange('y', minYValue, maxYValue); graphCubic(minXValue, maxXValue, minYValue, maxYValue, cubicCoeff, quadraticCoeff, linearCoeff, constantCoeff); return; } // This function queries the user for four values that will be used // // as polynomial coefficients for the cubic that is being graphed. // void queryUserForCoefficients(double &coeff3, double &coeff2, double &coeff1, double &coeff0) { coeff3 = queryUserForCoefficient(3); coeff2 = queryUserForCoefficient(2); coeff1 = queryUserForCoefficient(1); coeff0 = queryUserForCoefficient(0); cout << endl; return; } // The main function supervises querying the user for the // // cubic's coefficients and the range to be used within the // // x-y plane, as well as the actual graphing of the cubic. // void main() { double cubicCoeff, quadraticCoeff, linearCoeff, constantCoeff; int minXValue, maxXValue, minYValue, maxYValue; queryUserForCoefficients(cubicCoeff, quadraticCoeff, linearCoeff, constantCoeff); queryUserForRange('x', minXValue, maxXValue); queryUserForRange('y', minYValue, maxYValue); graphCubic(minXValue, maxXValue, minYValue, maxYValue, cubicCoeff, quadraticCoeff, linearCoeff, constantCoeff); return; } // This function queries the user for four values that will be used // // as polynomial coefficients for the cubic that is being graphed. // void queryUserForCoefficients(double &coeff3, double &coeff2, double &coeff1, double &coeff0) { coeff3 = queryUserForCoefficient(3); coeff2 = queryUserForCoefficient(2); coeff1 = queryUserForCoefficient(1); coeff0 = queryUserForCoefficient(0); cout << endl; return; }

11 // This function queries the user for the coefficient of the term // // of the cubic polynomial that has the parameterized exponent. // double queryUserForCoefficient(int exponent) { double coeff; cout << "Enter the coefficient of the "; switch (exponent) { case 3: { cout << "cubic"; break; } case 2: { cout << "quadratic"; break; } case 1: { cout << "linear"; break; } default: { cout << "constant"; break; } } cout << " term of the polynomial: "; switch (exponent) { case 3: { cout << " "; break; } case 1: { cout << " "; break; } case 0: { cout << " "; break; } } cin >> coeff; return coeff; } // This function queries the user for the coefficient of the term // // of the cubic polynomial that has the parameterized exponent. // double queryUserForCoefficient(int exponent) { double coeff; cout << "Enter the coefficient of the "; switch (exponent) { case 3: { cout << "cubic"; break; } case 2: { cout << "quadratic"; break; } case 1: { cout << "linear"; break; } default: { cout << "constant"; break; } } cout << " term of the polynomial: "; switch (exponent) { case 3: { cout << " "; break; } case 1: { cout << " "; break; } case 0: { cout << " "; break; } } cin >> coeff; return coeff; }

12 // This function queries the user for the minimum and maximum // // values for the specified axis. These values will be used // // to limit the range of the graphing of the cubic polynomial. // void queryUserForRange(char axisLabel, int &rangeMin, int &rangeMax) { cout << "Enter the range of " << axisLabel << "-values to be used in the graph." << endl; cout << "Minimum " << axisLabel << "-value: "; cin >> rangeMin; cout << "Maximum " << axisLabel << "-value: "; cin >> rangeMax; cout << endl; while (rangeMin >= rangeMax) { cout << "INAPPROPRIATE RANGE --- MAXIMUM MUST BE GREATER THAN MINIMUM." << endl; cout << "Enter the range of " << axisLabel << "-values to be used in the graph." << endl; cout << "Minimum " << axisLabel << "-value: "; cin >> rangeMin; cout << "Maximum " << axisLabel << "-value: "; cin >> rangeMax; cout << endl; } return; } // This function queries the user for the minimum and maximum // // values for the specified axis. These values will be used // // to limit the range of the graphing of the cubic polynomial. // void queryUserForRange(char axisLabel, int &rangeMin, int &rangeMax) { cout << "Enter the range of " << axisLabel << "-values to be used in the graph." << endl; cout << "Minimum " << axisLabel << "-value: "; cin >> rangeMin; cout << "Maximum " << axisLabel << "-value: "; cin >> rangeMax; cout << endl; while (rangeMin >= rangeMax) { cout << "INAPPROPRIATE RANGE --- MAXIMUM MUST BE GREATER THAN MINIMUM." << endl; cout << "Enter the range of " << axisLabel << "-values to be used in the graph." << endl; cout << "Minimum " << axisLabel << "-value: "; cin >> rangeMin; cout << "Maximum " << axisLabel << "-value: "; cin >> rangeMax; cout << endl; } return; }

13 // This function uses ASCII characters to graph the cubic polynomial // // with the parameterized coefficients within the parameterized range. // // Where appropriate, characters representing the axes will be output. // void graphCubic(int xMin, int xMax, int yMin, int yMax, double coeff3, double coeff2, double coeff1, double coeff0) { int yVal = yMax; outputLabel(coeff3, coeff2, coeff1, coeff0); while (yVal >= yMin) { outputStrip(yVal, xMin, xMax, coeff3, coeff2, coeff1, coeff0); yVal--; } cout << endl << endl; return; } // This function outputs the label identifying the // // precise cubic polynomial that is being graphed. // void outputLabel(double coeff3, double coeff2, double coeff1, double coeff0) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); cout << endl << "GRAPH OF f(x) = "; outputCubicTerm(coeff3); outputQuadraticTerm(coeff3, coeff2); outputLinearTerm(coeff3, coeff2, coeff1); outputConstantTerm(coeff3, coeff2, coeff1, coeff0); cout << endl << endl; return; } // This function uses ASCII characters to graph the cubic polynomial // // with the parameterized coefficients within the parameterized range. // // Where appropriate, characters representing the axes will be output. // void graphCubic(int xMin, int xMax, int yMin, int yMax, double coeff3, double coeff2, double coeff1, double coeff0) { int yVal = yMax; outputLabel(coeff3, coeff2, coeff1, coeff0); while (yVal >= yMin) { outputStrip(yVal, xMin, xMax, coeff3, coeff2, coeff1, coeff0); yVal--; } cout << endl << endl; return; } // This function outputs the label identifying the // // precise cubic polynomial that is being graphed. // void outputLabel(double coeff3, double coeff2, double coeff1, double coeff0) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); cout << endl << "GRAPH OF f(x) = "; outputCubicTerm(coeff3); outputQuadraticTerm(coeff3, coeff2); outputLinearTerm(coeff3, coeff2, coeff1); outputConstantTerm(coeff3, coeff2, coeff1, coeff0); cout << endl << endl; return; }

14 // This function outputs the cubic term of the polynomial // // being graphed, with special cases for cubic coefficient // // values of 0 (no output), 1 (no displayed coefficient), // // or -1 (a negative sign, but no displayed coefficient). // void outputCubicTerm(double coeff3) { if (coeff3 != 0.0) { if (coeff3 == -1.0) cout << '-'; else if (coeff3 != 1.0) cout << coeff3; cout << "x^3"; } return; } // This function outputs the cubic term of the polynomial // // being graphed, with special cases for cubic coefficient // // values of 0 (no output), 1 (no displayed coefficient), // // or -1 (a negative sign, but no displayed coefficient). // void outputCubicTerm(double coeff3) { if (coeff3 != 0.0) { if (coeff3 == -1.0) cout << '-'; else if (coeff3 != 1.0) cout << coeff3; cout << "x^3"; } return; } // This function outputs the quadratic term of the polynomial // // being graphed, with special cases for quadratic coefficient // // values of 0 (no output), 1 (no displayed coefficient), or // // -1 (a negative sign, but no displayed coefficient). // void outputQuadraticTerm(double coeff3, double coeff2) { if (coeff2 != 0.0) { if (coeff3 != 0.0) { if (coeff2 < 0.0) { cout << " - "; coeff2 *= -1; } else cout << " + "; } if (coeff2 != 1.0) cout << coeff2; cout << "x^2"; } return; } // This function outputs the quadratic term of the polynomial // // being graphed, with special cases for quadratic coefficient // // values of 0 (no output), 1 (no displayed coefficient), or // // -1 (a negative sign, but no displayed coefficient). // void outputQuadraticTerm(double coeff3, double coeff2) { if (coeff2 != 0.0) { if (coeff3 != 0.0) { if (coeff2 < 0.0) { cout << " - "; coeff2 *= -1; } else cout << " + "; } if (coeff2 != 1.0) cout << coeff2; cout << "x^2"; } return; }

15 // This function outputs the linear term of the polynomial // // being graphed, with special cases for linear coefficient // // values of 0 (no output), 1 (no displayed coefficient), // // or -1 (a negative sign, but no displayed coefficient). // void outputLinearTerm(double coeff3, double coeff2, double coeff1) { if (coeff1 != 0.0) { if ((coeff3 != 0.0) || (coeff2 != 0.0)) { if (coeff1 < 0.0) { cout << " - "; coeff1 *= -1; } else cout << " + "; } if (coeff1 != 1.0) cout << coeff1; cout << "x"; } return; } // This function outputs the linear term of the polynomial // // being graphed, with special cases for linear coefficient // // values of 0 (no output), 1 (no displayed coefficient), // // or -1 (a negative sign, but no displayed coefficient). // void outputLinearTerm(double coeff3, double coeff2, double coeff1) { if (coeff1 != 0.0) { if ((coeff3 != 0.0) || (coeff2 != 0.0)) { if (coeff1 < 0.0) { cout << " - "; coeff1 *= -1; } else cout << " + "; } if (coeff1 != 1.0) cout << coeff1; cout << "x"; } return; }

16 // This function outputs the constant term of the polynomial // // being graphed, with special cases for constant coefficient // // values of 0 (no output, unless there are no other terms in // // the polynomial) or nonzero (output the constant, prefaced // // with the appropriate mathematical operator if there are // // other terms in the polynomial). // void outputConstantTerm(double coeff3, double coeff2, double coeff1, double coeff0) { if (coeff0 == 0.0) { if ((coeff3 == 0) && (coeff2 == 0) && (coeff1 == 0)) cout << coeff0; } else { if ((coeff3 != 0.0) || (coeff2 != 0.0) || (coeff1 != 0.0)) { if (coeff0 < 0.0) cout << " - " << (-1 * coeff0); else cout << " + " << coeff0; } else cout << coeff0; } return; } // This function outputs the constant term of the polynomial // // being graphed, with special cases for constant coefficient // // values of 0 (no output, unless there are no other terms in // // the polynomial) or nonzero (output the constant, prefaced // // with the appropriate mathematical operator if there are // // other terms in the polynomial). // void outputConstantTerm(double coeff3, double coeff2, double coeff1, double coeff0) { if (coeff0 == 0.0) { if ((coeff3 == 0) && (coeff2 == 0) && (coeff1 == 0)) cout << coeff0; } else { if ((coeff3 != 0.0) || (coeff2 != 0.0) || (coeff1 != 0.0)) { if (coeff0 < 0.0) cout << " - " << (-1 * coeff0); else cout << " + " << coeff0; } else cout << coeff0; } return; }

17 // This function outputs the horizontal strip of characters // // representing the graph at a particular y-value, with a // // asterisks used to represent the graph itself, vertical // // bars, dashes, and plus signs used to represent the axes, // // and blanks used for all empty space. // void outputStrip(int yVal, int xMin, int xMax, double coeff3, double coeff2, double coeff1, double coeff0) { int xVal = xMin; while (xVal <= xMax) { if (closePoint(xVal, yVal, coeff3, coeff2, coeff1, coeff0)) cout << '*'; else if ((xVal == 0) && (yVal == 0)) cout << '+'; else if (xVal == 0) cout << '|'; else if (yVal == 0) cout << '-'; else cout << ' '; xVal++; } cout << endl; return; } // This function outputs the horizontal strip of characters // // representing the graph at a particular y-value, with a // // asterisks used to represent the graph itself, vertical // // bars, dashes, and plus signs used to represent the axes, // // and blanks used for all empty space. // void outputStrip(int yVal, int xMin, int xMax, double coeff3, double coeff2, double coeff1, double coeff0) { int xVal = xMin; while (xVal <= xMax) { if (closePoint(xVal, yVal, coeff3, coeff2, coeff1, coeff0)) cout << '*'; else if ((xVal == 0) && (yVal == 0)) cout << '+'; else if (xVal == 0) cout << '|'; else if (yVal == 0) cout << '-'; else cout << ' '; xVal++; } cout << endl; return; } // This function evaluates the cubic polynomial with // // the parameterized coefficients at the parameterized // // x-value, and determines whether the resulting y-value // // (after round-off) equals the parameterized y-value. // bool closePoint(int xVal, int yVal, double coeff3, double coeff2, double coeff1, double coeff0) { double actualY = coeff3 * pow(double(xVal), 3) + coeff2 * pow(double(xVal), 2) + coeff1 * xVal + coeff0; return (int(actualY) == yVal); } // This function evaluates the cubic polynomial with // // the parameterized coefficients at the parameterized // // x-value, and determines whether the resulting y-value // // (after round-off) equals the parameterized y-value. // bool closePoint(int xVal, int yVal, double coeff3, double coeff2, double coeff1, double coeff0) { double actualY = coeff3 * pow(double(xVal), 3) + coeff2 * pow(double(xVal), 2) + coeff1 * xVal + coeff0; return (int(actualY) == yVal); }

18

19 /////////////////////////////////////////////////////////////////// // This program demonstrates overloaded functions be utilizing // // two versions of the dot product function, one taking vectors // // of double coordinates and the other taking vectors of integer // // coordinates. // /////////////////////////////////////////////////////////////////// #include using namespace std; bool isInt(double value); double dotProduct(double x1, double y1, double x2, double y2); int dotProduct(int x1, int y1, int x2, int y2); char askForMore(); bool answerIsYes(char ltr); bool answerIsNo(char ltr); /////////////////////////////////////////////////////////////////// // This program demonstrates overloaded functions be utilizing // // two versions of the dot product function, one taking vectors // // of double coordinates and the other taking vectors of integer // // coordinates. // /////////////////////////////////////////////////////////////////// #include using namespace std; bool isInt(double value); double dotProduct(double x1, double y1, double x2, double y2); int dotProduct(int x1, int y1, int x2, int y2); char askForMore(); bool answerIsYes(char ltr); bool answerIsNo(char ltr);

20 // The main function coordinates the user queries // // and the output of dot product results. // void main() { double firstX, firstY, secondX, secondY; char yOrN = 'y'; while ( answerIsYes(yOrN) ) { cout << "Enter the coordinates for the first vector: "; cin >> firstX >> firstY; cout << "Enter the coordinates for the second vector: "; cin >> secondX >> secondY; if ( isInt(firstX) && isInt(firstY) && isInt(secondX) && isInt(secondY) ) cout << dotProduct( int(firstX), int(firstY), int(secondX), int(secondY) ); else cout << dotProduct( firstX, firstY, secondX, secondY ); cout << endl << endl; yOrN = askForMore(); } return; } // Returns a boolean flag indicating whether the // // parameterized double value has no fractional component. // bool isInt(double value) { return ( value - int(value) == 0.0 ); } // The main function coordinates the user queries // // and the output of dot product results. // void main() { double firstX, firstY, secondX, secondY; char yOrN = 'y'; while ( answerIsYes(yOrN) ) { cout << "Enter the coordinates for the first vector: "; cin >> firstX >> firstY; cout << "Enter the coordinates for the second vector: "; cin >> secondX >> secondY; if ( isInt(firstX) && isInt(firstY) && isInt(secondX) && isInt(secondY) ) cout << dotProduct( int(firstX), int(firstY), int(secondX), int(secondY) ); else cout << dotProduct( firstX, firstY, secondX, secondY ); cout << endl << endl; yOrN = askForMore(); } return; } // Returns a boolean flag indicating whether the // // parameterized double value has no fractional component. // bool isInt(double value) { return ( value - int(value) == 0.0 ); }

21 // Returns the dot product of two vectors of double values. // double dotProduct(double x1, double y1, double x2, double y2) { return (x1 * x2 + y1 * y2); } // Returns the dot product of two vectors of integer values. // int dotProduct(int x1, int y1, int x2, int y2) { return (x1 * x2 + y1 * y2); } // Queries the user for whether more dot product calculations are needed, // // compelling the user to respond with an appropriate character. // char askForMore() { char letter; cout << "Would you like to take another dot product? (Y or N) "; cin >> letter; while ( (!answerIsYes(letter)) && (!answerIsNo(letter)) ) { cout << "You must respond with the letter Y or the letter N!" << endl; cout << "Would you like to take another dot product? (Y or N) "; cin >> letter; } return letter; } // Returns the dot product of two vectors of double values. // double dotProduct(double x1, double y1, double x2, double y2) { return (x1 * x2 + y1 * y2); } // Returns the dot product of two vectors of integer values. // int dotProduct(int x1, int y1, int x2, int y2) { return (x1 * x2 + y1 * y2); } // Queries the user for whether more dot product calculations are needed, // // compelling the user to respond with an appropriate character. // char askForMore() { char letter; cout << "Would you like to take another dot product? (Y or N) "; cin >> letter; while ( (!answerIsYes(letter)) && (!answerIsNo(letter)) ) { cout << "You must respond with the letter Y or the letter N!" << endl; cout << "Would you like to take another dot product? (Y or N) "; cin >> letter; } return letter; }

22 // Returns a boolean flag indicating whether the parameterized // // character is the first letter of the word "yes". // bool answerIsYes(char ltr) { return ( (ltr == 'y') || (ltr == 'Y') ); } // Returns a boolean flag indicating whether the parameterized // // character is the first letter of the word "no". // bool answerIsNo(char ltr) { return ( (ltr == 'n') || (ltr == 'N') ); } // Returns a boolean flag indicating whether the parameterized // // character is the first letter of the word "yes". // bool answerIsYes(char ltr) { return ( (ltr == 'y') || (ltr == 'Y') ); } // Returns a boolean flag indicating whether the parameterized // // character is the first letter of the word "no". // bool answerIsNo(char ltr) { return ( (ltr == 'n') || (ltr == 'N') ); }

23 ///////////////////////////////////////////////////////// // This program reads date information from a specific // // text file, determining the percentage of dates in // // that file that utilize each of the twelve months. // ///////////////////////////////////////////////////////// #include using namespace std; int countData(); int countData(int month); // The main function supervises // // the retrieval of the date // // information and formats the // // program's output. // void main() { int month; int total; int count; double percent; ///////////////////////////////////////////////////////// // This program reads date information from a specific // // text file, determining the percentage of dates in // // that file that utilize each of the twelve months. // ///////////////////////////////////////////////////////// #include using namespace std; int countData(); int countData(int month); // The main function supervises // // the retrieval of the date // // information and formats the // // program's output. // void main() { int month; int total; int count; double percent; total = countData(); cout << " DATE FILE DATA ANALYSIS" << endl << " " << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(4); for (month = 1; month <= 12; month++) { count = countData(month); percent = * count / total; if (percent < 10.0) cout << " "; else if (percent < 100.0) cout << " "; cout << percent << "% of the dates are " << "from month #" << month << endl; } cout << endl << endl; return; } total = countData(); cout << " DATE FILE DATA ANALYSIS" << endl << " " << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(4); for (month = 1; month <= 12; month++) { count = countData(month); percent = * count / total; if (percent < 10.0) cout << " "; else if (percent < 100.0) cout << " "; cout << percent << "% of the dates are " << "from month #" << month << endl; } cout << endl << endl; return; }

24 // This function opens the date data file and counts // // the total number of dates contained therein. // int countData() { int count = 0; int month, day, year; ifstream dateFile; dateFile.open("dates.txt"); dateFile >> month; while ( !dateFile.eof() ) { dateFile >> day >> year; count++; dateFile >> month; } dateFile.close(); return count; } // This function opens the date data file and counts // // the total number of dates contained therein. // int countData() { int count = 0; int month, day, year; ifstream dateFile; dateFile.open("dates.txt"); dateFile >> month; while ( !dateFile.eof() ) { dateFile >> day >> year; count++; dateFile >> month; } dateFile.close(); return count; } // This function opens the date data file and counts // // the total number of dates contained therein that // // utilize the parameterized month. // int countData(int month) { int count = 0; int thisMonth, day, year; ifstream dateFile; dateFile.open("dates.txt"); dateFile >> thisMonth; while ( !dateFile.eof() ) { dateFile >> day >> year; if (thisMonth == month) count++; dateFile >> thisMonth } dateFile.close(); return count; } // This function opens the date data file and counts // // the total number of dates contained therein that // // utilize the parameterized month. // int countData(int month) { int count = 0; int thisMonth, day, year; ifstream dateFile; dateFile.open("dates.txt"); dateFile >> thisMonth; while ( !dateFile.eof() ) { dateFile >> day >> year; if (thisMonth == month) count++; dateFile >> thisMonth } dateFile.close(); return count; }

25 ////////////////////////////////////////////////////// // This program repeatedly asks the user for // // non-negative integer values and then recursively // // converts them into hexadecimal (base 16). // ////////////////////////////////////////////////////// #include using namespace std; int retrieveValue(); void convertToHexadecimal(int value); char hexDigit(int digit); bool queryForMore(); // The main function supervises the retrieval of data from // the user, the conversion of that data to hexadecimal, // and the determination of when the user is finished. void main() { int userValue; bool stillActive = true; while (stillActive) { userValue = retrieveValue(); cout << "HEXADECIMAL FORM OF " << userValue << " IS "; convertToHexadecimal(userValue); cout << endl << endl; stillActive = queryForMore(); } return; } ////////////////////////////////////////////////////// // This program repeatedly asks the user for // // non-negative integer values and then recursively // // converts them into hexadecimal (base 16). // ////////////////////////////////////////////////////// #include using namespace std; int retrieveValue(); void convertToHexadecimal(int value); char hexDigit(int digit); bool queryForMore(); // The main function supervises the retrieval of data from // the user, the conversion of that data to hexadecimal, // and the determination of when the user is finished. void main() { int userValue; bool stillActive = true; while (stillActive) { userValue = retrieveValue(); cout << "HEXADECIMAL FORM OF " << userValue << " IS "; convertToHexadecimal(userValue); cout << endl << endl; stillActive = queryForMore(); } return; }

26 // This function queries the user until supplied // with a non-negative integer value. int retrieveValue() { int integerValue; cout << "Please enter a non-negative integer: "; cin >> integerValue; while (integerValue < 0) { cout << endl << "Try again, The value must be non-negative: "; cin >> integerValue; } cout << endl; return integerValue; } // This function repeatedly divides the parameterized value by 16, // recursively converting the quotient into hexadecimal, followed // by outputting the remainder (an integer between 0 and 15) into // a single hexadecimal digit, which is output to the screen. void convertToHexadecimal(int value) { if (value < 16) cout << hexDigit(value); else { convertToHexadecimal(value / 16); cout << hexDigit(value % 16); } // This function queries the user until supplied // with a non-negative integer value. int retrieveValue() { int integerValue; cout << "Please enter a non-negative integer: "; cin >> integerValue; while (integerValue < 0) { cout << endl << "Try again, The value must be non-negative: "; cin >> integerValue; } cout << endl; return integerValue; } // This function repeatedly divides the parameterized value by 16, // recursively converting the quotient into hexadecimal, followed // by outputting the remainder (an integer between 0 and 15) into // a single hexadecimal digit, which is output to the screen. void convertToHexadecimal(int value) { if (value < 16) cout << hexDigit(value); else { convertToHexadecimal(value / 16); cout << hexDigit(value % 16); }

27 // This function converts the parameterized integer value (assumed // to between 0 and 15) into the corresponding hexadecimal digit. // The hexadecimal digit is returned as a character value. char hexDigit(int digit) { switch (digit) { case 10: { return 'A'; break; } case 11: { return 'B'; break; } case 12: { return 'C'; break; } case 13: { return 'D'; break; } case 14: { return 'E'; break; } case 15: { return 'F'; break; } default: { return char(digit + int('0')); break; } } // This function queries the user about additional input // until an appropriate character is entered, bool queryForMore() { char queryResponse; cout << "Would you like to convert another integer? (Y or N) "; cin >> queryResponse; while ( (queryResponse != 'y') && (queryResponse != 'Y') && (queryResponse != 'n') && (queryResponse != 'N') ) { cout << "You must enter Y for Yes or N for No." << endl << endl << "Would you like to convert another integer? (Y or N) "; cin >> queryResponse; } cout << endl; return ( (queryResponse == 'y') || (queryResponse == 'Y') ); } // This function converts the parameterized integer value (assumed // to between 0 and 15) into the corresponding hexadecimal digit. // The hexadecimal digit is returned as a character value. char hexDigit(int digit) { switch (digit) { case 10: { return 'A'; break; } case 11: { return 'B'; break; } case 12: { return 'C'; break; } case 13: { return 'D'; break; } case 14: { return 'E'; break; } case 15: { return 'F'; break; } default: { return char(digit + int('0')); break; } } // This function queries the user about additional input // until an appropriate character is entered, bool queryForMore() { char queryResponse; cout << "Would you like to convert another integer? (Y or N) "; cin >> queryResponse; while ( (queryResponse != 'y') && (queryResponse != 'Y') && (queryResponse != 'n') && (queryResponse != 'N') ) { cout << "You must enter Y for Yes or N for No." << endl << endl << "Would you like to convert another integer? (Y or N) "; cin >> queryResponse; } cout << endl; return ( (queryResponse == 'y') || (queryResponse == 'Y') ); }

28

29 /////////////////////////////////////////////// // This program queries the user for a // // chemical element and accesses an external // // file to retrieve data about that element. // /////////////////////////////////////////////// #include using namespace std; struct Element { int AtomicNumber; string Name; string Symbol; string ChemicalSeries; int Level1Electrons; int Level2Electrons; int Level3Electrons; int Level4Electrons; int Level5Electrons; int Level6Electrons; int Level7Electrons; }; Element queryUserForElement(); Element searchByAtomicNumber(ifstream &file); Element searchByAtomicSymbol(ifstream &file); void outputElement(Element elt); /////////////////////////////////////////////// // This program queries the user for a // // chemical element and accesses an external // // file to retrieve data about that element. // /////////////////////////////////////////////// #include using namespace std; struct Element { int AtomicNumber; string Name; string Symbol; string ChemicalSeries; int Level1Electrons; int Level2Electrons; int Level3Electrons; int Level4Electrons; int Level5Electrons; int Level6Electrons; int Level7Electrons; }; Element queryUserForElement(); Element searchByAtomicNumber(ifstream &file); Element searchByAtomicSymbol(ifstream &file); void outputElement(Element elt);

30 // The main function outputs a header and then supervises // the user query and the output of information about the // user-specified chemical element. void main() { Element elem; cout << "CHEMICAL ELEMENT DATA FINDER" << endl; cout << " " << endl; elem = queryUserForElement(); outputElement(elem); cout << endl << endl; return; } // This function coordinates the user query by first // determining whether the user wants to find the // chemical element by specifying its atomic number // or by specifying its atomic symbol. Element queryUserForElement() { Element elmnt; char searchChar; ifstream ElementFile; ElementFile.open("Elements.txt"); cout << "Enter # to search by atomic number," << endl << "anything else to search by atomic symbol: "; cin >> searchChar; if (searchChar == '#') elmnt = searchByAtomicNumber(ElementFile); else elmnt = searchByAtomicSymbol(ElementFile); ElementFile.close(); return elmnt; } // The main function outputs a header and then supervises // the user query and the output of information about the // user-specified chemical element. void main() { Element elem; cout << "CHEMICAL ELEMENT DATA FINDER" << endl; cout << " " << endl; elem = queryUserForElement(); outputElement(elem); cout << endl << endl; return; } // This function coordinates the user query by first // determining whether the user wants to find the // chemical element by specifying its atomic number // or by specifying its atomic symbol. Element queryUserForElement() { Element elmnt; char searchChar; ifstream ElementFile; ElementFile.open("Elements.txt"); cout << "Enter # to search by atomic number," << endl << "anything else to search by atomic symbol: "; cin >> searchChar; if (searchChar == '#') elmnt = searchByAtomicNumber(ElementFile); else elmnt = searchByAtomicSymbol(ElementFile); ElementFile.close(); return elmnt; }

31 // This function searches the parameterized input file for // a user-specified atomic number, returning the Element // that matches (or forcing the user to enter another // atomic number if the previous one was invalid). Element searchByAtomicNumber(ifstream &file) { int aNbr; int index; Element e; cout << "Enter the atomic number of the element being sought: "; cin >> aNbr; while ( (aNbr 118) ) { cout << "Atomic numbers are limited to the range." << endl << "Please try again: "; cin >> aNbr; } for (index = 1; index <= aNbr; index++) { file >> e.AtomicNumber; file >> e.Name; file >> e.Symbol; file >> e.ChemicalSeries; file >> e.Level1Electrons; file >> e.Level2Electrons; file >> e.Level3Electrons; file >> e.Level4Electrons; file >> e.Level5Electrons; file >> e.Level6Electrons; file >> e.Level7Electrons; } return e; } // This function searches the parameterized input file for // a user-specified atomic number, returning the Element // that matches (or forcing the user to enter another // atomic number if the previous one was invalid). Element searchByAtomicNumber(ifstream &file) { int aNbr; int index; Element e; cout << "Enter the atomic number of the element being sought: "; cin >> aNbr; while ( (aNbr 118) ) { cout << "Atomic numbers are limited to the range." << endl << "Please try again: "; cin >> aNbr; } for (index = 1; index <= aNbr; index++) { file >> e.AtomicNumber; file >> e.Name; file >> e.Symbol; file >> e.ChemicalSeries; file >> e.Level1Electrons; file >> e.Level2Electrons; file >> e.Level3Electrons; file >> e.Level4Electrons; file >> e.Level5Electrons; file >> e.Level6Electrons; file >> e.Level7Electrons; } return e; }

32 // This function searches the parameterized input file for // a user-specified atomic symbol, returning the Element // that matches (or forcing the user to enter another // atomic symbol if the previous one was invalid). Element searchByAtomicSymbol(ifstream &file) { bool foundElement = false; int aNbr; string aSym; Element e; cout << "Enter the atomic symbol of the element being sought: "; cin >> aSym; do { aNbr = 0; while ( (aNbr < 118) && (!foundElement) ) { aNbr++; file >> e.AtomicNumber; file >> e.Name; file >> e.Symbol; file >> e.ChemicalSeries; file >> e.Level1Electrons; file >> e.Level2Electrons; file >> e.Level3Electrons; file >> e.Level4Electrons; file >> e.Level5Electrons; file >> e.Level6Electrons; file >> e.Level7Electrons; foundElement = (e.Symbol == aSym); } // This function searches the parameterized input file for // a user-specified atomic symbol, returning the Element // that matches (or forcing the user to enter another // atomic symbol if the previous one was invalid). Element searchByAtomicSymbol(ifstream &file) { bool foundElement = false; int aNbr; string aSym; Element e; cout << "Enter the atomic symbol of the element being sought: "; cin >> aSym; do { aNbr = 0; while ( (aNbr < 118) && (!foundElement) ) { aNbr++; file >> e.AtomicNumber; file >> e.Name; file >> e.Symbol; file >> e.ChemicalSeries; file >> e.Level1Electrons; file >> e.Level2Electrons; file >> e.Level3Electrons; file >> e.Level4Electrons; file >> e.Level5Electrons; file >> e.Level6Electrons; file >> e.Level7Electrons; foundElement = (e.Symbol == aSym); } if (!foundElement) { cout << "The symbol you entered (" << aSym << ") is invalid." << endl << "Please try again: "; cin >> aSym; file.close(); file.open("Elements.txt"); } while (!foundElement); return e; } if (!foundElement) { cout << "The symbol you entered (" << aSym << ") is invalid." << endl << "Please try again: "; cin >> aSym; file.close(); file.open("Elements.txt"); } while (!foundElement); return e; }

33 // This function outputs the data associated with the parameterized chemical element. void outputElement(Element elt) { cout << endl << "Information about the element " << elt.Name << ":" << endl; cout << " Atomic Number: " << elt.AtomicNumber << endl; cout << " Atomic Symbol: " << elt.Symbol << endl; cout << " Chemical Series: " << elt.ChemicalSeries << endl; cout << "# Level 1 Electrons: " << elt.Level1Electrons << endl; if (elt.Level2Electrons > 0) { cout << "# Level 2 Electrons: " << elt.Level2Electrons << endl; if (elt.Level3Electrons > 0) { cout << "# Level 3 Electrons: " << elt.Level3Electrons << endl; if (elt.Level4Electrons > 0) { cout << "# Level 4 Electrons: " << elt.Level4Electrons << endl; if (elt.Level5Electrons > 0) { cout << "# Level 5 Electrons: " << elt.Level5Electrons << endl; if (elt.Level6Electrons > 0) { cout << "# Level 6 Electrons: " << elt.Level6Electrons << endl; if (elt.Level7Electrons > 0) cout << "# Level 7 Electrons: " << elt.Level7Electrons << endl; } return; } // This function outputs the data associated with the parameterized chemical element. void outputElement(Element elt) { cout << endl << "Information about the element " << elt.Name << ":" << endl; cout << " Atomic Number: " << elt.AtomicNumber << endl; cout << " Atomic Symbol: " << elt.Symbol << endl; cout << " Chemical Series: " << elt.ChemicalSeries << endl; cout << "# Level 1 Electrons: " << elt.Level1Electrons << endl; if (elt.Level2Electrons > 0) { cout << "# Level 2 Electrons: " << elt.Level2Electrons << endl; if (elt.Level3Electrons > 0) { cout << "# Level 3 Electrons: " << elt.Level3Electrons << endl; if (elt.Level4Electrons > 0) { cout << "# Level 4 Electrons: " << elt.Level4Electrons << endl; if (elt.Level5Electrons > 0) { cout << "# Level 5 Electrons: " << elt.Level5Electrons << endl; if (elt.Level6Electrons > 0) { cout << "# Level 6 Electrons: " << elt.Level6Electrons << endl; if (elt.Level7Electrons > 0) cout << "# Level 7 Electrons: " << elt.Level7Electrons << endl; } return; }

34 1 Hydrogen H Nonmetal Helium He NobleGas Lithium Li AlkaliMetal Beryllium Be AlkalineEarthMetal Boron B Metalloid Carbon C Nonmetal Nitrogen N Nonmetal Oxygen O Nonmetal Fluorine F Halogen Neon Ne NobleGas Sodium Na AlkaliMetal Magnesium Mg AlkalineEarthMetal Aluminium Al PoorMetal Silicon Si Metalloid Phosphorus P Nonmetal Sulfur S Nonmetal Chlorine Cl Halogen Argon Ar NobleGas Potassium K AlkaliMetal Calcium Ca AlkalineEarthMetal Scandium Sc TransitionMetal Titanium Ti TransitionMetal Vanadium V TransitionMetal Chromium Cr TransitionMetal Manganese Mn TransitionMetal Iron Fe TransitionMetal Cobalt Co TransitionMetal Nickel Ni TransitionMetal Copper Cu TransitionMetal Zinc Zn TransitionMetal Gallium Ga PoorMetal Germanium Ge Metalloid Arsenic As Metalloid Selenium Se Nonmetal Bromine Br Halogen Krypton Kr NobleGas Rubidium Rb AlkaliMetal Strontium Sr AlkalineEarthMetal Yttrium Y TransitionMetal Zirconium Zr TransitionMetal Niobium Nb TransitionMetal Molybdenum Mo TransitionMetal Technetium Tc TransitionMetal Ruthenium Ru TransitionMetal Rhodium Rh TransitionMetal Palladium Pd TransitionMetal Silver Ag TransitionMetal Cadmium Cd TransitionMetal Indium In PoorMetal Tin Sn PoorMetal Antimony Sb Metalloid Tellurium Te Metalloid Iodine I Halogen Xenon Xe NobleGas Caesium Cs AlkaliMetal Barium Ba AlkalineEarthMetal Lanthanum La Lanthanide Cerium Ce Lanthanide Praseodymium Pr Lanthanide Neodymium Nd Lanthanide Promethium Pm Lanthanide Samarium Sm Lanthanide Europium Eu Lanthanide Gadolinium Gd Lanthanide Terbium Tb Lanthanide Dysprosium Dy Lanthanide Holmium Ho Lanthanide Erbium Er Lanthanide Thulium Tm Lanthanide Ytterbium Yb Lanthanide Lutetium Lu Lanthanide Hafnium Hf TransitionMetal Tantalum Ta TransitionMetal Tungsten W TransitionMetal Rhenium Re TransitionMetal Osmium Os TransitionMetal Iridium Ir TransitionMetal Platinum Pt TransitionMetal Gold Au TransitionMetal Mercury Hg TransitionMetal Thallium Tl PoorMetal Lead Pb PoorMetal Bismuth Bi PoorMetal Polonium Po Metalloid Astatine At Halogen Radon Rn NobleGas Francium Fr AlkaliMetal Radium Ra AlkalineEarthMetal Actinium Ac Actinide Thorium Th Actinide Protactinium Pa Actinide Uranium U Actinide Neptunium Np Actinide Plutonium Pu Actinide Americium Am Actinide Curium Cm Actinide Berkelium Bk Actinide Californium Cf Actinide Einsteinium Es Actinide Fermium Fm Actinide Mendelevium Md Actinide Nobelium No Actinide Lawrencium Lr Actinide Rutherfordium Rf TransitionMetal Dubnium Db TransitionMetal Seaborgium Sg TransitionMetal Bohrium Bh TransitionMetal Hassium Hs TransitionMetal Meitnerium Mt TransitionMetal Darmstadtium Ds TransitionMetal Roentgenium Rg TransitionMetal Ununbium Uub TransitionMetal Ununtrium Uut PoorMetal Ununquadium Uuq PoorMetal Ununpentium Uup PoorMetal Ununhexium Uuh PoorMetal Ununseptium Uus Halogen Ununoctium Uuo NobleGas Hydrogen H Nonmetal Helium He NobleGas Lithium Li AlkaliMetal Beryllium Be AlkalineEarthMetal Boron B Metalloid Carbon C Nonmetal Nitrogen N Nonmetal Oxygen O Nonmetal Fluorine F Halogen Neon Ne NobleGas Sodium Na AlkaliMetal Magnesium Mg AlkalineEarthMetal Aluminium Al PoorMetal Silicon Si Metalloid Phosphorus P Nonmetal Sulfur S Nonmetal Chlorine Cl Halogen Argon Ar NobleGas Potassium K AlkaliMetal Calcium Ca AlkalineEarthMetal Scandium Sc TransitionMetal Titanium Ti TransitionMetal Vanadium V TransitionMetal Chromium Cr TransitionMetal Manganese Mn TransitionMetal Iron Fe TransitionMetal Cobalt Co TransitionMetal Nickel Ni TransitionMetal Copper Cu TransitionMetal Zinc Zn TransitionMetal Gallium Ga PoorMetal Germanium Ge Metalloid Arsenic As Metalloid Selenium Se Nonmetal Bromine Br Halogen Krypton Kr NobleGas Rubidium Rb AlkaliMetal Strontium Sr AlkalineEarthMetal Yttrium Y TransitionMetal Zirconium Zr TransitionMetal Niobium Nb TransitionMetal Molybdenum Mo TransitionMetal Technetium Tc TransitionMetal Ruthenium Ru TransitionMetal Rhodium Rh TransitionMetal Palladium Pd TransitionMetal Silver Ag TransitionMetal Cadmium Cd TransitionMetal Indium In PoorMetal Tin Sn PoorMetal Antimony Sb Metalloid Tellurium Te Metalloid Iodine I Halogen Xenon Xe NobleGas Caesium Cs AlkaliMetal Barium Ba AlkalineEarthMetal Lanthanum La Lanthanide Cerium Ce Lanthanide Praseodymium Pr Lanthanide Neodymium Nd Lanthanide Promethium Pm Lanthanide Samarium Sm Lanthanide Europium Eu Lanthanide Gadolinium Gd Lanthanide Terbium Tb Lanthanide Dysprosium Dy Lanthanide Holmium Ho Lanthanide Erbium Er Lanthanide Thulium Tm Lanthanide Ytterbium Yb Lanthanide Lutetium Lu Lanthanide Hafnium Hf TransitionMetal Tantalum Ta TransitionMetal Tungsten W TransitionMetal Rhenium Re TransitionMetal Osmium Os TransitionMetal Iridium Ir TransitionMetal Platinum Pt TransitionMetal Gold Au TransitionMetal Mercury Hg TransitionMetal Thallium Tl PoorMetal Lead Pb PoorMetal Bismuth Bi PoorMetal Polonium Po Metalloid Astatine At Halogen Radon Rn NobleGas Francium Fr AlkaliMetal Radium Ra AlkalineEarthMetal Actinium Ac Actinide Thorium Th Actinide Protactinium Pa Actinide Uranium U Actinide Neptunium Np Actinide Plutonium Pu Actinide Americium Am Actinide Curium Cm Actinide Berkelium Bk Actinide Californium Cf Actinide Einsteinium Es Actinide Fermium Fm Actinide Mendelevium Md Actinide Nobelium No Actinide Lawrencium Lr Actinide Rutherfordium Rf TransitionMetal Dubnium Db TransitionMetal Seaborgium Sg TransitionMetal Bohrium Bh TransitionMetal Hassium Hs TransitionMetal Meitnerium Mt TransitionMetal Darmstadtium Ds TransitionMetal Roentgenium Rg TransitionMetal Ununbium Uub TransitionMetal Ununtrium Uut PoorMetal Ununquadium Uuq PoorMetal Ununpentium Uup PoorMetal Ununhexium Uuh PoorMetal Ununseptium Uus Halogen Ununoctium Uuo NobleGas

35 Data Members ConstructorsAccessors Member Functions

36 ///////////////////////////////////////////////// // This program generates the data for circles // // and then draws them using ASCII characters. // ///////////////////////////////////////////////// #include using namespace std; const double PI = ; const int PADDING = 3; const int ASCII_ZERO_VALUE = 48; class Circle { public: // Constructor Circle(); // Member functions void setCoordinates(int x, int y); void setRadius(int r); void setASCIICharacter(char ch); double computeArea(); double computePerimeter(); void displayCircleAttributes(); void drawCircle(); // Accessor functions int getXCoord() const; int getYCoord() const; int getRadius() const; char getASCIICharacter() const; ///////////////////////////////////////////////// // This program generates the data for circles // // and then draws them using ASCII characters. // ///////////////////////////////////////////////// #include using namespace std; const double PI = ; const int PADDING = 3; const int ASCII_ZERO_VALUE = 48; class Circle { public: // Constructor Circle(); // Member functions void setCoordinates(int x, int y); void setRadius(int r); void setASCIICharacter(char ch); double computeArea(); double computePerimeter(); void displayCircleAttributes(); void drawCircle(); // Accessor functions int getXCoord() const; int getYCoord() const; int getRadius() const; char getASCIICharacter() const; private: // Data members int xCoord; int yCoord; int radius; char asciiCharacter; }; // This default constructor sets up the // // data members with default values. // Circle::Circle() { xCoord = yCoord = radius = 0; asciiCharacter = ' '; } // Assign the x- and y- coordinates of the // // circle's center with parameterized values. // void Circle::setCoordinates(int x, int y) { xCoord = x; yCoord = y; return; } // Assign the radius of the circle // // the parameterized value. // void Circle::setRadius(int r) { radius = r; return; } private: // Data members int xCoord; int yCoord; int radius; char asciiCharacter; }; // This default constructor sets up the // // data members with default values. // Circle::Circle() { xCoord = yCoord = radius = 0; asciiCharacter = ' '; } // Assign the x- and y- coordinates of the // // circle's center with parameterized values. // void Circle::setCoordinates(int x, int y) { xCoord = x; yCoord = y; return; } // Assign the radius of the circle // // the parameterized value. // void Circle::setRadius(int r) { radius = r; return; }

37 // Assign the fill character of the // // circle the parameterized value. // void Circle::setASCIICharacter(char ch) { asciiCharacter = ch; return; } // Compute and return the area of the circle. // double Circle::computeArea() { return PI * radius * radius; } // Compute and return the perimeter of the circle. // double Circle::computePerimeter() { return 2 * PI * radius; } // Output the circle's data member values, as // // well as the area and perimeter of the Circle. // void Circle::displayCircleAttributes() { cout.setf(ios::fixed); cout.precision(4); cout << "Center's x-coordinate: " << xCoord << endl; cout << "Center's y-coordinate: " << yCoord << endl; cout << "Circle's radius: " << radius << endl; cout << "Circle's area: " << computeArea() << endl; cout << "Circle's perimeter: " << computePerimeter() << endl; cout << "Circle's fill character: " << asciiCharacter << endl; } // Assign the fill character of the // // circle the parameterized value. // void Circle::setASCIICharacter(char ch) { asciiCharacter = ch; return; } // Compute and return the area of the circle. // double Circle::computeArea() { return PI * radius * radius; } // Compute and return the perimeter of the circle. // double Circle::computePerimeter() { return 2 * PI * radius; } // Output the circle's data member values, as // // well as the area and perimeter of the Circle. // void Circle::displayCircleAttributes() { cout.setf(ios::fixed); cout.precision(4); cout << "Center's x-coordinate: " << xCoord << endl; cout << "Center's y-coordinate: " << yCoord << endl; cout << "Circle's radius: " << radius << endl; cout << "Circle's area: " << computeArea() << endl; cout << "Circle's perimeter: " << computePerimeter() << endl; cout << "Circle's fill character: " << asciiCharacter << endl; }

38 // Output the Circle, using its ASCII character to draw it, // // as well as vertical and horizontal symbols to draw the // // coordinate axes, and an 'X' at the center of the circle. // void Circle::drawCircle() { const int PADDING = 4; const double HEIGHT_WIDTH_RATIO = 1.5; int x, y; int lowerX = (xCoord - radius < -PADDING) ? (xCoord - radius-PADDING) : -PADDING; int upperX = (xCoord + radius > PADDING) ? (xCoord + radius+PADDING) : PADDING; int lowerY = (yCoord - radius < -PADDING) ? (yCoord - radius-PADDING) : -PADDING; int upperY = (yCoord + radius > PADDING) ? (yCoord + radius+PADDING) : PADDING; for (y = upperY; y >= lowerY; y--) { for (x = int(HEIGHT_WIDTH_RATIO*lowerX); x <= int(HEIGHT_WIDTH_RATIO*upperX); x++) { if ((x == xCoord) && (y == yCoord)) cout << 'X'; else if (pow((x - xCoord) / HEIGHT_WIDTH_RATIO, 2) + pow(double(y - yCoord), 2) <= pow(double(radius), 2)) cout << asciiCharacter; else if ((x == 0) && (y == 0)) cout << '+'; else if (x == 0) cout << '|'; else if (y == 0) cout << '-'; else cout << ' '; } cout << endl; } // Output the Circle, using its ASCII character to draw it, // // as well as vertical and horizontal symbols to draw the // // coordinate axes, and an 'X' at the center of the circle. // void Circle::drawCircle() { const int PADDING = 4; const double HEIGHT_WIDTH_RATIO = 1.5; int x, y; int lowerX = (xCoord - radius < -PADDING) ? (xCoord - radius-PADDING) : -PADDING; int upperX = (xCoord + radius > PADDING) ? (xCoord + radius+PADDING) : PADDING; int lowerY = (yCoord - radius < -PADDING) ? (yCoord - radius-PADDING) : -PADDING; int upperY = (yCoord + radius > PADDING) ? (yCoord + radius+PADDING) : PADDING; for (y = upperY; y >= lowerY; y--) { for (x = int(HEIGHT_WIDTH_RATIO*lowerX); x <= int(HEIGHT_WIDTH_RATIO*upperX); x++) { if ((x == xCoord) && (y == yCoord)) cout << 'X'; else if (pow((x - xCoord) / HEIGHT_WIDTH_RATIO, 2) + pow(double(y - yCoord), 2) <= pow(double(radius), 2)) cout << asciiCharacter; else if ((x == 0) && (y == 0)) cout << '+'; else if (x == 0) cout << '|'; else if (y == 0) cout << '-'; else cout << ' '; } cout << endl; }

39 // Access and return the Circle's x-coordinate value. // int Circle::getXCoord() const { return xCoord; } // Access and return the Circle's y-coordinate value. // int Circle::getYCoord() const { return yCoord; } // Access and return the value of the Circle's radius. // int Circle::getRadius() const { return radius; } // Access and return the value of the Circle's ASCII fill character. // char Circle::getASCIICharacter() const { return asciiCharacter; } // Access and return the Circle's x-coordinate value. // int Circle::getXCoord() const { return xCoord; } // Access and return the Circle's y-coordinate value. // int Circle::getYCoord() const { return yCoord; } // Access and return the value of the Circle's radius. // int Circle::getRadius() const { return radius; } // Access and return the value of the Circle's ASCII fill character. // char Circle::getASCIICharacter() const { return asciiCharacter; }

40 ////////////////////////////////////////////////////////////////// // The main function serves as a driver to display a variety of // // circles with a variety of sizes, positions, and characters. // ////////////////////////////////////////////////////////////////// void main() { Circle circ; char YorN; int count = 1; int positionX = 4; int positionY = 2; cout << "Ready for the first circle? (Enter Y or N) "; cin >> YorN; while ((YorN == 'y') || (YorN == 'Y')) { circ.setASCIICharacter(char(ASCII_ZERO_VALUE + count)); circ.setRadius(count + 3); circ.setCoordinates(positionX,positionY); circ.displayCircleAttributes(); circ.drawCircle(); cout << "Ready for another circle? (Enter Y or N) "; cin >> YorN; count++; positionX = (positionX + 11) % 13; positionY = (positionY + 13) % 11; } return; } ////////////////////////////////////////////////////////////////// // The main function serves as a driver to display a variety of // // circles with a variety of sizes, positions, and characters. // ////////////////////////////////////////////////////////////////// void main() { Circle circ; char YorN; int count = 1; int positionX = 4; int positionY = 2; cout << "Ready for the first circle? (Enter Y or N) "; cin >> YorN; while ((YorN == 'y') || (YorN == 'Y')) { circ.setASCIICharacter(char(ASCII_ZERO_VALUE + count)); circ.setRadius(count + 3); circ.setCoordinates(positionX,positionY); circ.displayCircleAttributes(); circ.drawCircle(); cout << "Ready for another circle? (Enter Y or N) "; cin >> YorN; count++; positionX = (positionX + 11) % 13; positionY = (positionY + 13) % 11; } return; }

41

42 /////////////////////////////////////////////////////////////////////////////////////////////// // This header file contains the full definition of the Quadratic class, including // // constructors (default, initializing, and copy), accessors ("get" member functions for all // // data members), mutators ("set" member functions for all data members), and other member // // functions (evaluation, root determination, derivative, and input and output operators). // /////////////////////////////////////////////////////////////////////////////////////////////// #ifndef QUADRATIC_H #include using namespace std; // The class definition // class Quadratic { public: // Constructors Quadratic(); Quadratic(double quadratic, double linear, double constant); Quadratic(const Quadratic &quad); /////////////////////////////////////////////////////////////////////////////////////////////// // This header file contains the full definition of the Quadratic class, including // // constructors (default, initializing, and copy), accessors ("get" member functions for all // // data members), mutators ("set" member functions for all data members), and other member // // functions (evaluation, root determination, derivative, and input and output operators). // /////////////////////////////////////////////////////////////////////////////////////////////// #ifndef QUADRATIC_H #include using namespace std; // The class definition // class Quadratic { public: // Constructors Quadratic(); Quadratic(double quadratic, double linear, double constant); Quadratic(const Quadratic &quad);

43 // Accessors double getQuadratic() const; double getLinear() const; double getConstant() const; void getCoefficients(double &quadratic, double &linear, double &constant) const; // Mutators void setQuadratic(double quadratic); void setLinear(double linear); void setConstant(double constant); void setCoefficients(double quadratic, double linear, double constant); // Member Functions double evaluateAt(double x); bool getRoots(double &x1, double &x2); Quadratic derivative(); friend ostream& operator << (ostream &outputFile, const Quadratic &quad); friend istream& operator >> (istream &inputFile, Quadratic &quad); private: // Data Members double quadraticCoefficient; double linearCoefficient; double constantCoefficient; }; // Accessors double getQuadratic() const; double getLinear() const; double getConstant() const; void getCoefficients(double &quadratic, double &linear, double &constant) const; // Mutators void setQuadratic(double quadratic); void setLinear(double linear); void setConstant(double constant); void setCoefficients(double quadratic, double linear, double constant); // Member Functions double evaluateAt(double x); bool getRoots(double &x1, double &x2); Quadratic derivative(); friend ostream& operator << (ostream &outputFile, const Quadratic &quad); friend istream& operator >> (istream &inputFile, Quadratic &quad); private: // Data Members double quadraticCoefficient; double linearCoefficient; double constantCoefficient; };

44 // Default Constructor // // Sets all coefficients to zero initially. // Quadratic::Quadratic() { quadraticCoefficient = 0.0; linearCoefficient = 0.0; constantCoefficient = 0.0; return; } // Initializing Constructor // // Sets all coefficients to parameterized values. // Quadratic::Quadratic(double quadratic, double linear, double constant) { quadraticCoefficient = quadratic; linearCoefficient = linear; constantCoefficient = constant; return; } // Copy Constructor // // Sets all coefficients to the same values // // as the parameterized Quadratic. // Quadratic::Quadratic(const Quadratic &quad) { quadraticCoefficient = quad.quadraticCoefficient; linearCoefficient = quad.linearCoefficient; constantCoefficient = quad.constantCoefficient; return; } // Default Constructor // // Sets all coefficients to zero initially. // Quadratic::Quadratic() { quadraticCoefficient = 0.0; linearCoefficient = 0.0; constantCoefficient = 0.0; return; } // Initializing Constructor // // Sets all coefficients to parameterized values. // Quadratic::Quadratic(double quadratic, double linear, double constant) { quadraticCoefficient = quadratic; linearCoefficient = linear; constantCoefficient = constant; return; } // Copy Constructor // // Sets all coefficients to the same values // // as the parameterized Quadratic. // Quadratic::Quadratic(const Quadratic &quad) { quadraticCoefficient = quad.quadraticCoefficient; linearCoefficient = quad.linearCoefficient; constantCoefficient = quad.constantCoefficient; return; }

45 // Quadratic Coefficient Accessor // double Quadratic::getQuadratic() const { return quadraticCoefficient; } // Linear Corfficient Accessor // double Quadratic::getLinear() const { return linearCoefficient; } // Constant Coefficient Accessor // double Quadratic::getConstant() const { return constantCoefficient; } // All-Coefficient Accessor // void Quadratic::getCoefficients(double &quadratic, double &linear, double &constant) const { quadratic = quadraticCoefficient; linear = linearCoefficient; constant = constantCoefficient; } // Quadratic Coefficient Accessor // double Quadratic::getQuadratic() const { return quadraticCoefficient; } // Linear Corfficient Accessor // double Quadratic::getLinear() const { return linearCoefficient; } // Constant Coefficient Accessor // double Quadratic::getConstant() const { return constantCoefficient; } // All-Coefficient Accessor // void Quadratic::getCoefficients(double &quadratic, double &linear, double &constant) const { quadratic = quadraticCoefficient; linear = linearCoefficient; constant = constantCoefficient; }

46 // Quadratic Coefficient Mutator // void Quadratic::setQuadratic(double quadratic) { quadraticCoefficient = quadratic; } // Linear Coefficient Mutator // void Quadratic::setLinear(double linear) { linearCoefficient = linear; } // Constant Coefficient Mutator // void Quadratic::setConstant(double constant) { constantCoefficient = constant; } // All-Coefficient Mutator // void Quadratic::setCoefficients(double quadratic, double linear, double constant) { quadraticCoefficient = quadratic; linearCoefficient = linear; constantCoefficient = constant; } // Quadratic Coefficient Mutator // void Quadratic::setQuadratic(double quadratic) { quadraticCoefficient = quadratic; } // Linear Coefficient Mutator // void Quadratic::setLinear(double linear) { linearCoefficient = linear; } // Constant Coefficient Mutator // void Quadratic::setConstant(double constant) { constantCoefficient = constant; } // All-Coefficient Mutator // void Quadratic::setCoefficients(double quadratic, double linear, double constant) { quadraticCoefficient = quadratic; linearCoefficient = linear; constantCoefficient = constant; }

47 // Evaluation Member Function // // Returns the evaluation of the quadratic // // equation at the parameterized x-value. // double Quadratic::evaluateAt(double x) { return quadraticCoefficient * x * x + linearCoefficient * x + constantCoefficient; } // Root Determination Member Function // // Obtains the roots of the quadratic equation, // // returning a boolean flag that indicates // // whether the root or roots are real. // bool Quadratic::getRoots(double &x1, double &x2) { double discriminant; // If the quadratic is actually a constant, set the return flag to false // if ( (quadraticCoefficient == 0) && (linearCoefficient == 0) ) return false; // If the quadratic is actually linear, the root is the solution to the linear equation. // else if (quadraticCoefficient == 0) { x1 = x2 = -constantCoefficient / linearCoefficient; return true; } // Evaluation Member Function // // Returns the evaluation of the quadratic // // equation at the parameterized x-value. // double Quadratic::evaluateAt(double x) { return quadraticCoefficient * x * x + linearCoefficient * x + constantCoefficient; } // Root Determination Member Function // // Obtains the roots of the quadratic equation, // // returning a boolean flag that indicates // // whether the root or roots are real. // bool Quadratic::getRoots(double &x1, double &x2) { double discriminant; // If the quadratic is actually a constant, set the return flag to false // if ( (quadraticCoefficient == 0) && (linearCoefficient == 0) ) return false; // If the quadratic is actually linear, the root is the solution to the linear equation. // else if (quadraticCoefficient == 0) { x1 = x2 = -constantCoefficient / linearCoefficient; return true; }

48 // If the quadratic is really a quadratic, use the quadratic // // formula to determine its roots, if they happen to be real values. // else { discriminant = linearCoefficient * linearCoefficient - 4 * quadraticCoefficient * constantCoefficient; if (discriminant < 0) return false; else { x1 = (-linearCoefficient – sqrt(discriminant)) / (2 * quadraticCoefficient); x2 = (-linearCoefficient + sqrt(discriminant)) / (2 * quadraticCoefficient); return true; } // Derivative Member Function // // Returns the first derivative of the Quadratic. // Quadratic Quadratic::derivative() { Quadratic derivQuad(0.0, 2 * quadraticCoefficient, linearCoefficient); return derivQuad; } // If the quadratic is really a quadratic, use the quadratic // // formula to determine its roots, if they happen to be real values. // else { discriminant = linearCoefficient * linearCoefficient - 4 * quadraticCoefficient * constantCoefficient; if (discriminant < 0) return false; else { x1 = (-linearCoefficient – sqrt(discriminant)) / (2 * quadraticCoefficient); x2 = (-linearCoefficient + sqrt(discriminant)) / (2 * quadraticCoefficient); return true; } // Derivative Member Function // // Returns the first derivative of the Quadratic. // Quadratic Quadratic::derivative() { Quadratic derivQuad(0.0, 2 * quadraticCoefficient, linearCoefficient); return derivQuad; }

49 // Overloaded Output Operator // // Outputs the Quadratic in "ax^2 + bx + c" form, unless // // the quadratic coefficient is zero ("bx + c") or both // // the quadratic and linear coefficients are zero ("c"). // ostream& operator << (ostream &outputFile, const Quadratic &quad) { if (quad.quadraticCoefficient != 0.0) outputFile << quad.quadraticCoefficient << "x^2"; if (quad.linearCoefficient != 0.0) { if (quad.quadraticCoefficient == 0.0) outputFile << quad.linearCoefficient << "x"; else if (quad.linearCoefficient < 0.0) outputFile << " - " << -quad.linearCoefficient << "x"; else outputFile << " + " << quad.linearCoefficient << "x"; } if ( (quad.quadraticCoefficient == 0.0) && (quad.linearCoefficient == 0.0) ) outputFile << quad.constantCoefficient; else if (quad.constantCoefficient < 0.0) outputFile << " - " << -quad.constantCoefficient; else if (quad.constantCoefficient > 0.0) outputFile << " + " << quad.constantCoefficient; return outputFile; } // Overloaded Output Operator // // Outputs the Quadratic in "ax^2 + bx + c" form, unless // // the quadratic coefficient is zero ("bx + c") or both // // the quadratic and linear coefficients are zero ("c"). // ostream& operator << (ostream &outputFile, const Quadratic &quad) { if (quad.quadraticCoefficient != 0.0) outputFile << quad.quadraticCoefficient << "x^2"; if (quad.linearCoefficient != 0.0) { if (quad.quadraticCoefficient == 0.0) outputFile << quad.linearCoefficient << "x"; else if (quad.linearCoefficient < 0.0) outputFile << " - " << -quad.linearCoefficient << "x"; else outputFile << " + " << quad.linearCoefficient << "x"; } if ( (quad.quadraticCoefficient == 0.0) && (quad.linearCoefficient == 0.0) ) outputFile << quad.constantCoefficient; else if (quad.constantCoefficient < 0.0) outputFile << " - " << -quad.constantCoefficient; else if (quad.constantCoefficient > 0.0) outputFile << " + " << quad.constantCoefficient; return outputFile; }

50 // Overloaded Input Operator // // Inputs the three coefficients // // from the designated input file. // istream& operator >> (istream &inputFile, Quadratic &quad) { inputFile >> quad.quadraticCoefficient >> quad.linearCoefficient >> quad.constantCoefficient; return inputFile; } #define QUADRATIC_H #endif // Overloaded Input Operator // // Inputs the three coefficients // // from the designated input file. // istream& operator >> (istream &inputFile, Quadratic &quad) { inputFile >> quad.quadraticCoefficient >> quad.linearCoefficient >> quad.constantCoefficient; return inputFile; } #define QUADRATIC_H #endif

51 ////////////////////////////////////////////////////////// // This driver program requests a Quadratic from the // // user and outputs its roots (if any), its derivative, // // and its minimum or maximum point (if any). // ////////////////////////////////////////////////////////// #include #include "Quadratic.h" using namespace std; Quadratic requestQuadratic(); // The main function handles all program activity in the driver, // // except for the user query for the Quadratic's coefficients. // void main() { Quadratic quadro; Quadratic firstDerivative; double root1, root2; double maxmin1, maxmin2; cout << "Initial Quadratic: f(x) = " << quadro << endl << endl; quadro = requestQuadratic(); cout << endl << "Current Quadratic: f(x) = " << quadro << endl << endl; if ( quadro.getRoots(root1, root2) ) cout << " Roots: " << root1 << " and " << root2 << endl << endl; else cout << " No real roots to this quadratic." << endl << endl; ////////////////////////////////////////////////////////// // This driver program requests a Quadratic from the // // user and outputs its roots (if any), its derivative, // // and its minimum or maximum point (if any). // ////////////////////////////////////////////////////////// #include #include "Quadratic.h" using namespace std; Quadratic requestQuadratic(); // The main function handles all program activity in the driver, // // except for the user query for the Quadratic's coefficients. // void main() { Quadratic quadro; Quadratic firstDerivative; double root1, root2; double maxmin1, maxmin2; cout << "Initial Quadratic: f(x) = " << quadro << endl << endl; quadro = requestQuadratic(); cout << endl << "Current Quadratic: f(x) = " << quadro << endl << endl; if ( quadro.getRoots(root1, root2) ) cout << " Roots: " << root1 << " and " << root2 << endl << endl; else cout << " No real roots to this quadratic." << endl << endl;

52 firstDerivative = quadro.derivative(); cout << " Derivative: f'(x) = " << firstDerivative << endl << endl; if ( firstDerivative.getRoots(maxmin1, maxmin2) ) { if (quadro.evaluateAt(maxmin1) < quadro.evaluateAt(maxmin )) cout << " Parabolic Minimum At x = " << maxmin1 << " (y = " << quadro.evaluateAt(maxmin1) << ")" << endl << endl; else cout << " Parabolic Maximum At x = " << maxmin1 << " (y = " << quadro.evaluateAt(maxmin1) << ")" << endl << endl; } return; } // The requestQuadratic function queries the user for the // // Quadratic coefficients and returns the resulting Quadratic. // Quadratic requestQuadratic() { Quadratic quad; cout << "Enter the coefficients of a quadratic equation," << endl << "in order, beginning with the quadratic term: "; cin >> quad; return quad; } firstDerivative = quadro.derivative(); cout << " Derivative: f'(x) = " << firstDerivative << endl << endl; if ( firstDerivative.getRoots(maxmin1, maxmin2) ) { if (quadro.evaluateAt(maxmin1) < quadro.evaluateAt(maxmin )) cout << " Parabolic Minimum At x = " << maxmin1 << " (y = " << quadro.evaluateAt(maxmin1) << ")" << endl << endl; else cout << " Parabolic Maximum At x = " << maxmin1 << " (y = " << quadro.evaluateAt(maxmin1) << ")" << endl << endl; } return; } // The requestQuadratic function queries the user for the // // Quadratic coefficients and returns the resulting Quadratic. // Quadratic requestQuadratic() { Quadratic quad; cout << "Enter the coefficients of a quadratic equation," << endl << "in order, beginning with the quadratic term: "; cin >> quad; return quad; }

53 ///////////////////////////////////////////////////////////////////////// // This driver program requests a projectile's angle and initial speed // // and calculates the peak and the landing distance of its trajectory. // ///////////////////////////////////////////////////////////////////////// #include #include "Quadratic.h" using namespace std; const double PI = ; const double GRAVITATIONAL_ACCELERATION = ; Quadratic getTrajectoryQuadratic(); // The main function handles all program activity in the driver, // // except for the user query for the Quadratic's coefficients. // void main() { Quadratic quad; Quadratic firstDerivative; double root1, root2; double maxmin1, maxmin2; cout << "PROJECTILE TRAJECTORY CALCULATION" << endl; cout << " " << endl; quad = getTrajectoryQuadratic(); ///////////////////////////////////////////////////////////////////////// // This driver program requests a projectile's angle and initial speed // // and calculates the peak and the landing distance of its trajectory. // ///////////////////////////////////////////////////////////////////////// #include #include "Quadratic.h" using namespace std; const double PI = ; const double GRAVITATIONAL_ACCELERATION = ; Quadratic getTrajectoryQuadratic(); // The main function handles all program activity in the driver, // // except for the user query for the Quadratic's coefficients. // void main() { Quadratic quad; Quadratic firstDerivative; double root1, root2; double maxmin1, maxmin2; cout << "PROJECTILE TRAJECTORY CALCULATION" << endl; cout << " " << endl; quad = getTrajectoryQuadratic();

54 cout << "Landing distance: "; quad.getRoots(root1, root2); (root1 != 0.0) ? (cout << root1) : (cout << root2); cout << " feet" << endl; firstDerivative = quad.derivative(); firstDerivative.getRoots(maxmin1, maxmin2); cout << "Peak height: " << maxmin1 << " feet" << endl << endl; return; } // This function queries the user regarding the projectile's initial velocity // and angle, and returns the quadratic corresponding to its trajectory. Quadratic getTrajectoryQuadratic() { Quadratic q; double theta; double initialVelocity; cout << "Enter the initial velocity of the projectile (in feet/second): "; cin >> initialVelocity; cout << "Enter the projectile's initial angle (in degrees): "; cin >> theta; theta *= (PI / 180); q.setCoefficients( -GRAVITATIONAL_ACCELERATION / (2 * pow(initialVelocity * cos(theta), 2)), tan(theta), 0.0); return q; } cout << "Landing distance: "; quad.getRoots(root1, root2); (root1 != 0.0) ? (cout << root1) : (cout << root2); cout << " feet" << endl; firstDerivative = quad.derivative(); firstDerivative.getRoots(maxmin1, maxmin2); cout << "Peak height: " << maxmin1 << " feet" << endl << endl; return; } // This function queries the user regarding the projectile's initial velocity // and angle, and returns the quadratic corresponding to its trajectory. Quadratic getTrajectoryQuadratic() { Quadratic q; double theta; double initialVelocity; cout << "Enter the initial velocity of the projectile (in feet/second): "; cin >> initialVelocity; cout << "Enter the projectile's initial angle (in degrees): "; cin >> theta; theta *= (PI / 180); q.setCoefficients( -GRAVITATIONAL_ACCELERATION / (2 * pow(initialVelocity * cos(theta), 2)), tan(theta), 0.0); return q; }

55

56 //////////////////////////////////////////////////////// // This program examines an external file composed of // // temperature readings, placing the highest values // // in an array that is then output to the user. // //////////////////////////////////////////////////////// #include using namespace std; const int MAX_LIST_SIZE = 10; void loadList(double list[], int &listSize); void insertNewHighValue(double list[], int listSize, double highVal); void outputList(double list[], int listSize); // The main function merely coordinates the list creation and output. void main() { double highVal[MAX_LIST_SIZE]; int nbrOfVals; loadList(highVal, nbrOfVals); outputList(highVal, nbrOfVals); return; } //////////////////////////////////////////////////////// // This program examines an external file composed of // // temperature readings, placing the highest values // // in an array that is then output to the user. // //////////////////////////////////////////////////////// #include using namespace std; const int MAX_LIST_SIZE = 10; void loadList(double list[], int &listSize); void insertNewHighValue(double list[], int listSize, double highVal); void outputList(double list[], int listSize); // The main function merely coordinates the list creation and output. void main() { double highVal[MAX_LIST_SIZE]; int nbrOfVals; loadList(highVal, nbrOfVals); outputList(highVal, nbrOfVals); return; }

57 // The loadList function opens the input file, reads all of its // data, retaining the highest values in the parameterized array. void loadList(double list[], int &listSize) { double newVal; ifstream valFile; listSize = 0; valFile.open("TempReadings.txt"); valFile >> newVal; while (!valFile.eof()) { if (listSize < MAX_LIST_SIZE) { list[listSize] = newVal; listSize++; } else insertNewHighValue(list, listSize, newVal); valFile >> newVal; } valFile.close(); return; } // The loadList function opens the input file, reads all of its // data, retaining the highest values in the parameterized array. void loadList(double list[], int &listSize) { double newVal; ifstream valFile; listSize = 0; valFile.open("TempReadings.txt"); valFile >> newVal; while (!valFile.eof()) { if (listSize < MAX_LIST_SIZE) { list[listSize] = newVal; listSize++; } else insertNewHighValue(list, listSize, newVal); valFile >> newVal; } valFile.close(); return; }

58 // The insertNewHighValue function determines whether the // parameterized newVal is larger in value than any of the // values in the parameterized array. If so, the smallest // such value is replaced in the array with newVal. void insertNewHighValue(double list[], int listSize, double newVal) { int i; int lowValIndex = 0; for (i = 0; i < listSize; i++) if (list[i] < list[lowValIndex]) lowValIndex = i; if (newVal > list[lowValIndex]) list[lowValIndex] = newVal; return; } // The outputList function outputs the contents of the // parameterized array to the user, using a stylized format. void outputList(double list[], int listSize) { int i; cout << setw(20) << "Highest Values" << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(5); for (i = 0; i < listSize; i++) cout << setw(17) << list[i] << endl; cout << endl; return; } // The insertNewHighValue function determines whether the // parameterized newVal is larger in value than any of the // values in the parameterized array. If so, the smallest // such value is replaced in the array with newVal. void insertNewHighValue(double list[], int listSize, double newVal) { int i; int lowValIndex = 0; for (i = 0; i < listSize; i++) if (list[i] < list[lowValIndex]) lowValIndex = i; if (newVal > list[lowValIndex]) list[lowValIndex] = newVal; return; } // The outputList function outputs the contents of the // parameterized array to the user, using a stylized format. void outputList(double list[], int listSize) { int i; cout << setw(20) << "Highest Values" << endl; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(5); for (i = 0; i < listSize; i++) cout << setw(17) << list[i] << endl; cout << endl; return; }

59 ////////////////////////////////////////////////////////// // The Element class represents a chemical element // // with data members for the atomic number, the name, // // the symbol, the chemicalseries, and the number of // // electrons in each of the seven electron levels. It // // also provides overloaded input and output operators. // ////////////////////////////////////////////////////////// #ifndef ELEMENT_H #include using namespace std; class Element { public: // Constructors Element(); Element(const Element &elt); // Accessors int getAtomicNumber() const; string getName() const; string getSymbol() const; string getChemicalSeries() const; void getElectrons(int elec[]) const; ////////////////////////////////////////////////////////// // The Element class represents a chemical element // // with data members for the atomic number, the name, // // the symbol, the chemicalseries, and the number of // // electrons in each of the seven electron levels. It // // also provides overloaded input and output operators. // ////////////////////////////////////////////////////////// #ifndef ELEMENT_H #include using namespace std; class Element { public: // Constructors Element(); Element(const Element &elt); // Accessors int getAtomicNumber() const; string getName() const; string getSymbol() const; string getChemicalSeries() const; void getElectrons(int elec[]) const;

60 // Mutators void setAtomicNumber(int aNbr); void setName(string nm); void setSymbol(string sym); void setChemicalSeries(string ser); void setElectrons(int elec[]); // Overloaded Operators friend ostream& operator << (ostream &outputFile, const Element &elt); friend istream& operator >> (istream &inputFile, Element &elt); private: // Data Members int AtomicNumber; string Name; string Symbol; string ChemicalSeries; int Electrons[7]; }; // Default Constructor: Sets new // Element to hydrogen by default. Element::Element() { int i; AtomicNumber = 1; Name = "Hydrogen"; Symbol = "H"; ChemicalSeries = "Nonmetal"; Electrons[0] = 1; for (i = 1; i < 7; i++) Electrons[i] = 0; } // Mutators void setAtomicNumber(int aNbr); void setName(string nm); void setSymbol(string sym); void setChemicalSeries(string ser); void setElectrons(int elec[]); // Overloaded Operators friend ostream& operator << (ostream &outputFile, const Element &elt); friend istream& operator >> (istream &inputFile, Element &elt); private: // Data Members int AtomicNumber; string Name; string Symbol; string ChemicalSeries; int Electrons[7]; }; // Default Constructor: Sets new // Element to hydrogen by default. Element::Element() { int i; AtomicNumber = 1; Name = "Hydrogen"; Symbol = "H"; ChemicalSeries = "Nonmetal"; Electrons[0] = 1; for (i = 1; i < 7; i++) Electrons[i] = 0; } // Copy Constructor: Duplicates parameterized Element. Element::Element(const Element &elt) { int i; AtomicNumber = elt.AtomicNumber; Name = elt.Name; Symbol = elt.Symbol; ChemicalSeries = elt.ChemicalSeries; for (i = 0; i < 7; i++) Electrons[i] = elt.Electrons[i]; } // Atomic Number Accessor: Retrieves value. int Element::getAtomicNumber() const { return AtomicNumber; } // Name Accessor: Retrieves value. string Element::getName() const { return Name; } // Copy Constructor: Duplicates parameterized Element. Element::Element(const Element &elt) { int i; AtomicNumber = elt.AtomicNumber; Name = elt.Name; Symbol = elt.Symbol; ChemicalSeries = elt.ChemicalSeries; for (i = 0; i < 7; i++) Electrons[i] = elt.Electrons[i]; } // Atomic Number Accessor: Retrieves value. int Element::getAtomicNumber() const { return AtomicNumber; } // Name Accessor: Retrieves value. string Element::getName() const { return Name; }

61 // Symbol Accessor: Retrieves value. string Element::getSymbol() const { return Symbol; } // Chemical Series Accessor: Retrieves value, padding with blanks to separate words. string Element::getChemicalSeries() const { int index = 1; string revisedSeries = ChemicalSeries; while (index < int(revisedSeries.length())) { if ( (revisedSeries[index] >= 'A') && (revisedSeries[index] <= 'Z') && (revisedSeries[index - 1] >= 'a') && (revisedSeries[index - 1] <= 'z') ) revisedSeries = revisedSeries.substr(0, index) + " " + revisedSeries.substr(index, revisedSeries.length() - index); index++; } return revisedSeries; } // Electrons Accessor: Retrieves values. void Element::getElectrons(int elec[]) const { int i; for (i = 0; i < 7; i++) elec[i] = Electrons[i]; } // Symbol Accessor: Retrieves value. string Element::getSymbol() const { return Symbol; } // Chemical Series Accessor: Retrieves value, padding with blanks to separate words. string Element::getChemicalSeries() const { int index = 1; string revisedSeries = ChemicalSeries; while (index < int(revisedSeries.length())) { if ( (revisedSeries[index] >= 'A') && (revisedSeries[index] <= 'Z') && (revisedSeries[index - 1] >= 'a') && (revisedSeries[index - 1] <= 'z') ) revisedSeries = revisedSeries.substr(0, index) + " " + revisedSeries.substr(index, revisedSeries.length() - index); index++; } return revisedSeries; } // Electrons Accessor: Retrieves values. void Element::getElectrons(int elec[]) const { int i; for (i = 0; i < 7; i++) elec[i] = Electrons[i]; }

62 // Atomic Number Mutator // Sets value, using 1 if parameter's value is invalid. void Element::setAtomicNumber(int aNbr) { if ( (aNbr 118) ) AtomicNumber = 1; else AtomicNumber = aNbr; } // Name Mutator // Sets value to parameterized value. void Element::setName(string nm) { Name = nm; } // Symbol Mutator // Sets value to parameterized value. void Element::setSymbol(string sym) { Symbol = sym; } // Chemical Series Mutator // Sets value to parameterized value. void Element::setChemicalSeries(string ser) { ChemicalSeries = ser; } // Atomic Number Mutator // Sets value, using 1 if parameter's value is invalid. void Element::setAtomicNumber(int aNbr) { if ( (aNbr 118) ) AtomicNumber = 1; else AtomicNumber = aNbr; } // Name Mutator // Sets value to parameterized value. void Element::setName(string nm) { Name = nm; } // Symbol Mutator // Sets value to parameterized value. void Element::setSymbol(string sym) { Symbol = sym; } // Chemical Series Mutator // Sets value to parameterized value. void Element::setChemicalSeries(string ser) { ChemicalSeries = ser; } // Electrons Mutator: Sets values to // parameterized values, correcting // for non-zeros after first zero. void Element::setElectrons(int elec[]) { int i; bool previousWasZero = false; for (i = 0; i < 7; i++) { if (previousWasZero) Electrons[i] = 0; else { Electrons[i] = elec[i]; if (Electrons[i] == 0) previousWasZero = true; } // Electrons Mutator: Sets values to // parameterized values, correcting // for non-zeros after first zero. void Element::setElectrons(int elec[]) { int i; bool previousWasZero = false; for (i = 0; i < 7; i++) { if (previousWasZero) Electrons[i] = 0; else { Electrons[i] = elec[i]; if (Electrons[i] == 0) previousWasZero = true; }

63 // Output Operator: Outputs Element data members in formatted fashion. ostream& operator << (ostream &outputFile, const Element &elt) { int i; outputFile << elt.Name + " (" + elt.Symbol + ")" << endl; outputFile << " Atomic Number: " << elt.AtomicNumber << endl; outputFile << " Chemical Series: " << elt.getChemicalSeries() << endl; outputFile << " Electron Levels: {"; for (i = 0; i < 7; i++) { outputFile << elt.Electrons[i]; if (i < 6) outputFile << ", "; else outputFile << "}"; } return outputFile; } // Input Operator: Inputs Element data members, assuming a specific format. istream& operator >> (istream &inputFile, Element &elt) { int i; inputFile >> elt.AtomicNumber >> elt.Name >> elt.Symbol >> elt.ChemicalSeries; for (i = 0; i < 7; i++) inputFile >> elt.Electrons[i]; return inputFile; } #define ELEMENT_H #endif // Output Operator: Outputs Element data members in formatted fashion. ostream& operator << (ostream &outputFile, const Element &elt) { int i; outputFile << elt.Name + " (" + elt.Symbol + ")" << endl; outputFile << " Atomic Number: " << elt.AtomicNumber << endl; outputFile << " Chemical Series: " << elt.getChemicalSeries() << endl; outputFile << " Electron Levels: {"; for (i = 0; i < 7; i++) { outputFile << elt.Electrons[i]; if (i < 6) outputFile << ", "; else outputFile << "}"; } return outputFile; } // Input Operator: Inputs Element data members, assuming a specific format. istream& operator >> (istream &inputFile, Element &elt) { int i; inputFile >> elt.AtomicNumber >> elt.Name >> elt.Symbol >> elt.ChemicalSeries; for (i = 0; i < 7; i++) inputFile >> elt.Electrons[i]; return inputFile; } #define ELEMENT_H #endif

64 /////////////////////////////////////////////////////////////// // This program employs the previously defined Element class // // to load a dynamic array with all elements whose names and // // symbols don't appear to correspond (i.e., characters in // // the symbol that do not appear in the name). The results // // are then output to the user. // /////////////////////////////////////////////////////////////// #include #include "Element.h" using namespace std; void retrieveOddSymbols(Element* &list, int &listSize); bool nameSymbolMismatch(Element elt); void alphabetizeOddSymbols(Element list[], int listSize); void reportOddSymbols(Element list[], int listSize); // The main function coordinates the program's activity by out- // putting a header and then calling functions to make the list // of elements with name-symbol mismatches, to alphabetize those // elements (by name), and to output the final alphabetized list. void main() { Element* oddElement; int nbrOddElements; cout << "CHEMICAL ELEMENTS WITH NAME-SYMBOL MISMATCHES" << endl << endl; retrieveOddSymbols(oddElement, nbrOddElements); alphabetizeOddSymbols(oddElement, nbrOddElements); reportOddSymbols(oddElement, nbrOddElements); delete[] oddElement; } /////////////////////////////////////////////////////////////// // This program employs the previously defined Element class // // to load a dynamic array with all elements whose names and // // symbols don't appear to correspond (i.e., characters in // // the symbol that do not appear in the name). The results // // are then output to the user. // /////////////////////////////////////////////////////////////// #include #include "Element.h" using namespace std; void retrieveOddSymbols(Element* &list, int &listSize); bool nameSymbolMismatch(Element elt); void alphabetizeOddSymbols(Element list[], int listSize); void reportOddSymbols(Element list[], int listSize); // The main function coordinates the program's activity by out- // putting a header and then calling functions to make the list // of elements with name-symbol mismatches, to alphabetize those // elements (by name), and to output the final alphabetized list. void main() { Element* oddElement; int nbrOddElements; cout << "CHEMICAL ELEMENTS WITH NAME-SYMBOL MISMATCHES" << endl << endl; retrieveOddSymbols(oddElement, nbrOddElements); alphabetizeOddSymbols(oddElement, nbrOddElements); reportOddSymbols(oddElement, nbrOddElements); delete[] oddElement; }

65 // This function creates the dynamic array of elements by first counting how // many elements have mismatched names and symbols, allocating memory for an // array of that size, and then loading the mismatched elements into that array. void retrieveOddSymbols(Element* &list, int &listSize) { int eltNbr; int oddEltNbr; ifstream eltFile; Element nextElt; eltFile.open("Elements.txt"); listSize = 0; for (eltNbr = 1; eltNbr <= 118; eltNbr++) { eltFile >> nextElt; if (nameSymbolMismatch(nextElt)) listSize++; } eltFile.close(); list = new Element[listSize]; eltFile.open("Elements.txt"); oddEltNbr = 0; for (eltNbr = 1; eltNbr <= 118; eltNbr++) { eltFile >> nextElt; if (nameSymbolMismatch(nextElt)) { list[oddEltNbr] = nextElt; oddEltNbr++; } eltFile.close(); return; } // This function creates the dynamic array of elements by first counting how // many elements have mismatched names and symbols, allocating memory for an // array of that size, and then loading the mismatched elements into that array. void retrieveOddSymbols(Element* &list, int &listSize) { int eltNbr; int oddEltNbr; ifstream eltFile; Element nextElt; eltFile.open("Elements.txt"); listSize = 0; for (eltNbr = 1; eltNbr <= 118; eltNbr++) { eltFile >> nextElt; if (nameSymbolMismatch(nextElt)) listSize++; } eltFile.close(); list = new Element[listSize]; eltFile.open("Elements.txt"); oddEltNbr = 0; for (eltNbr = 1; eltNbr <= 118; eltNbr++) { eltFile >> nextElt; if (nameSymbolMismatch(nextElt)) { list[oddEltNbr] = nextElt; oddEltNbr++; } eltFile.close(); return; }

66 // This function determines whether the parameterized Element // has a name-symbol mismatch by searching the name for each // character in the symbol. If any symbol character is not // found in the name, the function returns a boolean flag // indicating that the Element has a mismatch. bool nameSymbolMismatch(Element elt) { int symbolIndex = 0; int nameIndex; bool symbolCharFound = true; char symbolChar; while ( symbolIndex < int(elt.getSymbol().length()) ) { symbolChar = elt.getSymbol().at(symbolIndex); symbolCharFound = false; nameIndex = 0; while ( (!symbolCharFound) && (nameIndex < int(elt.getName().length())) ) { if (elt.getName().at(nameIndex) == symbolChar) symbolCharFound = true; else nameIndex++; } if (symbolCharFound) symbolIndex++; else return true; } return false; } // This function determines whether the parameterized Element // has a name-symbol mismatch by searching the name for each // character in the symbol. If any symbol character is not // found in the name, the function returns a boolean flag // indicating that the Element has a mismatch. bool nameSymbolMismatch(Element elt) { int symbolIndex = 0; int nameIndex; bool symbolCharFound = true; char symbolChar; while ( symbolIndex < int(elt.getSymbol().length()) ) { symbolChar = elt.getSymbol().at(symbolIndex); symbolCharFound = false; nameIndex = 0; while ( (!symbolCharFound) && (nameIndex < int(elt.getName().length())) ) { if (elt.getName().at(nameIndex) == symbolChar) symbolCharFound = true; else nameIndex++; } if (symbolCharFound) symbolIndex++; else return true; } return false; }

67 // This function places the parameterized Element array in alphabetical // order, according to the names of the Elements. It accomplishes this // by swapping the Element with the name that comes first alphabetically // with the first array Element, the second with the second, and so forth. void alphabetizeOddSymbols(Element list[], int listSize) { Element tempElement; int currentIndex, smallestElementIndex, possibleSwapIndex; for (currentIndex = 0; currentIndex < listSize - 1; currentIndex++) { smallestElementIndex = currentIndex; for (possibleSwapIndex = currentIndex + 1; possibleSwapIndex < listSize; possibleSwapIndex++) if (list[possibleSwapIndex].getName() < list[smallestElementIndex].getName()) smallestElementIndex = possibleSwapIndex; if (smallestElementIndex != currentIndex) { tempElement = list[currentIndex]; list[currentIndex] = list[smallestElementIndex]; list[smallestElementIndex] = tempElement; } return; } // This function uses the Element output operator to output the // list of Elements with mismatched names and symbols to the user. void reportOddSymbols(Element list[], int listSize) { int eltIndex; for (eltIndex = 0; eltIndex < listSize; eltIndex++) cout << list[eltIndex] << endl << endl; return; } // This function places the parameterized Element array in alphabetical // order, according to the names of the Elements. It accomplishes this // by swapping the Element with the name that comes first alphabetically // with the first array Element, the second with the second, and so forth. void alphabetizeOddSymbols(Element list[], int listSize) { Element tempElement; int currentIndex, smallestElementIndex, possibleSwapIndex; for (currentIndex = 0; currentIndex < listSize - 1; currentIndex++) { smallestElementIndex = currentIndex; for (possibleSwapIndex = currentIndex + 1; possibleSwapIndex < listSize; possibleSwapIndex++) if (list[possibleSwapIndex].getName() < list[smallestElementIndex].getName()) smallestElementIndex = possibleSwapIndex; if (smallestElementIndex != currentIndex) { tempElement = list[currentIndex]; list[currentIndex] = list[smallestElementIndex]; list[smallestElementIndex] = tempElement; } return; } // This function uses the Element output operator to output the // list of Elements with mismatched names and symbols to the user. void reportOddSymbols(Element list[], int listSize) { int eltIndex; for (eltIndex = 0; eltIndex < listSize; eltIndex++) cout << list[eltIndex] << endl << endl; return; }

68 1 Hydrogen H Nonmetal Helium He NobleGas Lithium Li AlkaliMetal Beryllium Be AlkalineEarthMetal Boron B Metalloid Carbon C Nonmetal Nitrogen N Nonmetal Oxygen O Nonmetal Fluorine F Halogen Neon Ne NobleGas Sodium Na AlkaliMetal Magnesium Mg AlkalineEarthMetal Aluminium Al PoorMetal Silicon Si Metalloid Phosphorus P Nonmetal Sulfur S Nonmetal Chlorine Cl Halogen Argon Ar NobleGas Potassium K AlkaliMetal Calcium Ca AlkalineEarthMetal Scandium Sc TransitionMetal Titanium Ti TransitionMetal Vanadium V TransitionMetal Chromium Cr TransitionMetal Manganese Mn TransitionMetal Iron Fe TransitionMetal Cobalt Co TransitionMetal Nickel Ni TransitionMetal Copper Cu TransitionMetal Zinc Zn TransitionMetal Gallium Ga PoorMetal Germanium Ge Metalloid Arsenic As Metalloid Selenium Se Nonmetal Bromine Br Halogen Krypton Kr NobleGas Rubidium Rb AlkaliMetal Strontium Sr AlkalineEarthMetal Yttrium Y TransitionMetal Zirconium Zr TransitionMetal Niobium Nb TransitionMetal Molybdenum Mo TransitionMetal Technetium Tc TransitionMetal Ruthenium Ru TransitionMetal Rhodium Rh TransitionMetal Palladium Pd TransitionMetal Silver Ag TransitionMetal Cadmium Cd TransitionMetal Indium In PoorMetal Tin Sn PoorMetal Antimony Sb Metalloid Tellurium Te Metalloid Iodine I Halogen Xenon Xe NobleGas Caesium Cs AlkaliMetal Barium Ba AlkalineEarthMetal Lanthanum La Lanthanide Cerium Ce Lanthanide Praseodymium Pr Lanthanide Neodymium Nd Lanthanide Promethium Pm Lanthanide Samarium Sm Lanthanide Europium Eu Lanthanide Gadolinium Gd Lanthanide Terbium Tb Lanthanide Dysprosium Dy Lanthanide Holmium Ho Lanthanide Erbium Er Lanthanide Thulium Tm Lanthanide Ytterbium Yb Lanthanide Lutetium Lu Lanthanide Hafnium Hf TransitionMetal Tantalum Ta TransitionMetal Tungsten W TransitionMetal Rhenium Re TransitionMetal Osmium Os TransitionMetal Iridium Ir TransitionMetal Platinum Pt TransitionMetal Gold Au TransitionMetal Mercury Hg TransitionMetal Thallium Tl PoorMetal Lead Pb PoorMetal Bismuth Bi PoorMetal Polonium Po Metalloid Astatine At Halogen Radon Rn NobleGas Francium Fr AlkaliMetal Radium Ra AlkalineEarthMetal Actinium Ac Actinide Thorium Th Actinide Protactinium Pa Actinide Uranium U Actinide Neptunium Np Actinide Plutonium Pu Actinide Americium Am Actinide Curium Cm Actinide Berkelium Bk Actinide Californium Cf Actinide Einsteinium Es Actinide Fermium Fm Actinide Mendelevium Md Actinide Nobelium No Actinide Lawrencium Lr Actinide Rutherfordium Rf TransitionMetal Dubnium Db TransitionMetal Seaborgium Sg TransitionMetal Bohrium Bh TransitionMetal Hassium Hs TransitionMetal Meitnerium Mt TransitionMetal Darmstadtium Ds TransitionMetal Roentgenium Rg TransitionMetal Ununbium Uub TransitionMetal Ununtrium Uut PoorMetal Ununquadium Uuq PoorMetal Ununpentium Uup PoorMetal Ununhexium Uuh PoorMetal Ununseptium Uus Halogen Ununoctium Uuo NobleGas Hydrogen H Nonmetal Helium He NobleGas Lithium Li AlkaliMetal Beryllium Be AlkalineEarthMetal Boron B Metalloid Carbon C Nonmetal Nitrogen N Nonmetal Oxygen O Nonmetal Fluorine F Halogen Neon Ne NobleGas Sodium Na AlkaliMetal Magnesium Mg AlkalineEarthMetal Aluminium Al PoorMetal Silicon Si Metalloid Phosphorus P Nonmetal Sulfur S Nonmetal Chlorine Cl Halogen Argon Ar NobleGas Potassium K AlkaliMetal Calcium Ca AlkalineEarthMetal Scandium Sc TransitionMetal Titanium Ti TransitionMetal Vanadium V TransitionMetal Chromium Cr TransitionMetal Manganese Mn TransitionMetal Iron Fe TransitionMetal Cobalt Co TransitionMetal Nickel Ni TransitionMetal Copper Cu TransitionMetal Zinc Zn TransitionMetal Gallium Ga PoorMetal Germanium Ge Metalloid Arsenic As Metalloid Selenium Se Nonmetal Bromine Br Halogen Krypton Kr NobleGas Rubidium Rb AlkaliMetal Strontium Sr AlkalineEarthMetal Yttrium Y TransitionMetal Zirconium Zr TransitionMetal Niobium Nb TransitionMetal Molybdenum Mo TransitionMetal Technetium Tc TransitionMetal Ruthenium Ru TransitionMetal Rhodium Rh TransitionMetal Palladium Pd TransitionMetal Silver Ag TransitionMetal Cadmium Cd TransitionMetal Indium In PoorMetal Tin Sn PoorMetal Antimony Sb Metalloid Tellurium Te Metalloid Iodine I Halogen Xenon Xe NobleGas Caesium Cs AlkaliMetal Barium Ba AlkalineEarthMetal Lanthanum La Lanthanide Cerium Ce Lanthanide Praseodymium Pr Lanthanide Neodymium Nd Lanthanide Promethium Pm Lanthanide Samarium Sm Lanthanide Europium Eu Lanthanide Gadolinium Gd Lanthanide Terbium Tb Lanthanide Dysprosium Dy Lanthanide Holmium Ho Lanthanide Erbium Er Lanthanide Thulium Tm Lanthanide Ytterbium Yb Lanthanide Lutetium Lu Lanthanide Hafnium Hf TransitionMetal Tantalum Ta TransitionMetal Tungsten W TransitionMetal Rhenium Re TransitionMetal Osmium Os TransitionMetal Iridium Ir TransitionMetal Platinum Pt TransitionMetal Gold Au TransitionMetal Mercury Hg TransitionMetal Thallium Tl PoorMetal Lead Pb PoorMetal Bismuth Bi PoorMetal Polonium Po Metalloid Astatine At Halogen Radon Rn NobleGas Francium Fr AlkaliMetal Radium Ra AlkalineEarthMetal Actinium Ac Actinide Thorium Th Actinide Protactinium Pa Actinide Uranium U Actinide Neptunium Np Actinide Plutonium Pu Actinide Americium Am Actinide Curium Cm Actinide Berkelium Bk Actinide Californium Cf Actinide Einsteinium Es Actinide Fermium Fm Actinide Mendelevium Md Actinide Nobelium No Actinide Lawrencium Lr Actinide Rutherfordium Rf TransitionMetal Dubnium Db TransitionMetal Seaborgium Sg TransitionMetal Bohrium Bh TransitionMetal Hassium Hs TransitionMetal Meitnerium Mt TransitionMetal Darmstadtium Ds TransitionMetal Roentgenium Rg TransitionMetal Ununbium Uub TransitionMetal Ununtrium Uut PoorMetal Ununquadium Uuq PoorMetal Ununpentium Uup PoorMetal Ununhexium Uuh PoorMetal Ununseptium Uus Halogen Ununoctium Uuo NobleGas


Download ppt "////////////////////////////////////////////////////// // This program retrieves dimensional box data from // // a user-specified input file and determines."

Similar presentations


Ads by Google