You are on page 1of 41

Absolute C++ 6th Edition Savitch

Solutions Manual
Visit to download the full and correct content document:
https://testbankdeal.com/download/absolute-c-6th-edition-savitch-solutions-manual/
Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

Chapter 6
Structures and Classes
Key Terms
structure
struct
structure tag
member name
where to place a structure definition
structure value
member value
member variable
reusing member names
structure variables in assignment statements
structure arguments
functions can return structures
class
object
member function
calling member functions
defining member functions
scope resolution operator
type qualifier
member variables in function definitions
data types and abstract types
encapsulation
private:
private member variable
public:
public member variable
accessor function
mutator function
interface
API
implementation

Brief Outline
6.1 Structures
Structure Types
Structures as Function Arguments
Initializing Structures
6.2 Classes
Defining Classes and Member Functions
Encapsulation
Public and Private Members

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

Accessor and Mutator Functions


Structures versus Classes

1. Introduction and Teaching Suggestions


In earlier chapters, we saw the array, the first of the C++ tools for creating data structures. The
other tools are the struct and the class. We saw that the array provides a homogeneous,
random access data structure. This chapter introduces tools to create heterogenous data
structures, namely the struct and class. While the struct and class are identical except for default
access, the text takes the didactic approach of first ignoring struct function members. This
chapter deals with the struct as C treats it. The text then develops the simpler ideas involved in
declaration and access for the struct. Then the machinery of class creation, protection
mechanisms and some ideas of encapsulation of functions with data are treated. Constructors are
left to Chapter 7.

2. Key Points

Structures and Structure Types. Historical note: The name struct in C++ is provided
primarily for backward compatibility with ANSI C. Suppose we declare a struct, as in:
struct B
{
int x;
int y;
};
The text points out that the identifier B is called the structure tag. The structure tag B carries full
type information. The tag B can be used as you would use any built-in type. The identifiers x and
y declared in the definition of struct B are called member names. The members are variables are
associated with any variable of struct type. You can declare a variable of type B by writing1
B u;
You can access member variables (as l-values) by writing
u.x = 1;
u.y = 2;
or (as r-values)
int p, q;
p = u.x;
q = u.y;
We said in the previous paragraph that the tag B can be used as you would use any built-in type.
You can pass a struct to a function as a parameter, use a struct as a function return type, and
declare arrays of variables of type struct.

1
Contrast this with the C usage, struct B u;, where the keyword struct must be used in the definition of a
structure variable. This use is permitted in C++ for backward compatibility with C.

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

Our author points out that two identifiers that are declared to be of the same structure type may be
assigned, with member-wise assignment occurring.2 The critical issue here is that for assignment
compatibility the two structure variables must be declared with the same structure tag. In the
example that follows, the types are indistinguishable from the member structure within the struct.
However, C++ uses name equivalence for types, so the compiler looks at the tags in the
declarations rather than the structure to determine whether one struct variable may be assigned to
another. Example:
struct A
{
int x;
int y;
};
struct B
{
int x;
int y;
};
A u;
B v;
u = v; //type error: u and v are of different types
The error message from g++ 2.9.5 is:
// no match for 'A& = B&'
// candidates are: struct A& A::operator=(const A&)

Structures as Function Arguments. Since a structure tag is a type, the tag can be used as any other
type would be used. You can have arrays of structure objects, or function parameters that are call-by-value
or call-by-reference, and you can use a structure a type for the return type of a function.

Defining Classes and Member Functions. These remarks elaborate the ideas in the text on
class and the scope resolution operator, ::. A class definition (and a struct definition as well),
with the {}; define a scope within which variables and functions are defined. They are not
accessible outside without qualification by the object name and a dot operator . Member
functions are defined within a particular class, to be used by any object declared to be of that
class, again, only with qualification by being preceded by the object name and the dot operator.
To define a function whose prototype is given in a class we have to specify the scope of that
class within which the function is being defined. This is done with the class tag and scope
resolution operator.
To say:
returnTypeName class_tag::funcMemberName(argumentList)
{
//memberFunctionBody...
}
is to say "Within the scope of the class class_tag, define the function named funcMemberName
that has return type returnTypeName."

2
Member-wise assignment is the default for classes and structs. A former student of mine, John Gibson coined the
phrase, “Member UNWISE copy”. We will see that for classes with pointer members, member (un)wise copy is
almost never what you want.

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

The data members belong to a particular object, and function members must be called on behalf
of that particular object. The object must be specified. The object is specified by using the dot
operator used after the object name, before the member name or function call. Sometimes we
may speak of the calling object.

Encapsulation. The notion of encapsulation means, “to collect together, as if to place in a


capsule”, from which we may infer the purpose, “to hide the details”. The text says a data type
has a set of values to be manipulated, and sets of operations to manipulate the values, but the
details are available to the user or client. A data type becomes an abstract data type if the client
does not have access to the implementation details.

Abstract Data Types. The notion of Abstract Data Type (ADT) has two players: the author of
the ADT and the client of the ADT. The client knows only what the ADT will do, not how the
ADT carries out its tasks. The author of the ADT knows only what the ADT will do for the
client, but nothing about the context within which the ADT is used by the client. Information
hiding is a two way hiding. The separation of implementation (known only to the class author)
and the interface (the contract between ADT author and client) is vital. The other side of the
coin, namely the concealment from the ADT author of the context within which the ADT will be
used, is equally vital. This prevents either author from writing code that would depend on the
internals written by the other programmer.

Separate compilation is necessary to a) concealing implementation details and b) assigning tasks


to several programmers in a team. The reason for leaving the interface and the implementation of
the ADTs in the client in the text is that we do not yet know anything about separate compilation.
Observe that the text almost always places declarations (prototypes) prior to use, then uses the
functions in the main function, then tucks the definitions away after the main function. This has
the effect of emphasizing separation of definition and declaration well before separate
compilation is seen by the student. This is worth mentioning to the student.

Public and Private Members. The data members of a class are part of the implementation, not
part of the interface. The function members intended for use by the client are the interface. There
may be helping functions for the implementation that would be inappropriate for the client to
use, and so are not part of the interface. Normally the interface is made available to the client and
the implementation is hidden.

A struct, by default, allows access to its members by any function. A class, by default, allows
access to its members only to those functions declared within the class. This default access in a
struct is called public, and the default access in a class is called private.

The keywords private and public help manage hiding the implementation and making the
interface available to the client. These keywords are used to modify the default access to
members of a class or struct. The keyword private is used to hide members. The effect of the
keyword private: extends from the keyword private: to the next instance of the keyword public:.
The effect of the keyword public: extends from the keyword public: up to the next instance of the
keyword private:.

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

Accessor and Mutator Functions. It is the class author who writes the accessor and mutator
functions, so it is she who controls the access to the class data. If the data members were public,
any function has access in any way the client wishes. Data integrity will be compromised.

Structures versus Classes. This is the text’s “truth in advertising” section. Since this document
is for the instructor, little distinction between structs and classes is made here.

3. Tips
Hierarchical Structures. It is worth pointing out that the name spaces for hierarchical (or
nested) structures are separate. The same names can be used in the containing struct as are used
in the structure member. The same names can be used in two structures members at the same
level.
Example: Name space and hierarchical structure initialization
// file: ch6test2.cc
// purpose: test namespace in hierarchical structures
#include <iostream>
using namespace std;
struct A
{
int a;
int b;
};
struct B
{
A c;
int a;
int b;
};
int main()
{
A u = {1,2};
B v = {{3,4},4,5};
cout << "u.a = " << u.a << " u.b = " << u.b << endl;
cout << "v.c.a = " << v.c.a << " v.c.b = " << v.c.b
<< " v.a = " << v.a << " v.b = " << v.b << endl;
return 0;
}
This code compiles and runs as expected. The output is:
u.a = 1 u.b = 2
v.c.a = 3 v.c.b = 4 v.a = 4 v.b = 5
This is, of course, a "horrible example", designed to show a worst case. One would almost never
use the same identifiers in two structures while using a struct object as a member of another as
we do here. However, this does serve to illustrate the idea that the name spaces for two structures
are separate. (This is also true for classes as well.) In short, duplicating a member name where
needed won't break a program.

Initializing Structures. The previous example also illustrates that structure variables can be
assigned initial values using the curly brace notation.

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

Separate Interface and Implementation. The interface provides the API and helps abstract the
implementation details from a user of the class. This allows a programmer to change the
implementation without having to change other parts of the program.

A Test for Encapsulation. If you can change the implementation of a class without requiring a
change to the client code, you have the implementation adequately encapsulated.

Thinking Objects. When programming with classes, data rather than algorithms takes center
stage. The difference is in the point of view compared to students that have never programmed
with objects before.

4. Pitfalls
Omitting the semicolon at the end of a struct or class definition. The text points out that a
structure definition is required to have a semicolon following the closing curly brace. The reason
is that it is possible to define a variable of the struct type by putting the identifier between the
closed curly brace, }, and the semicolon.
struct A
{
int a;
int b;
} c;
The variable c is of struct type A. With some compilers, this pitfall generates particularly
uninformative error messages. It will be quite helpful for the student to write several examples in
which the closing semicolon in a structure definition is deliberately omitted.

5. Programming Projects Answers


1. Class grading program

//ch6Prg1.cpp

#include <iostream>
using namespace std;

const int CLASS_SIZE = 5;

// Problem says this is for a class, rather than one student.


// Strategy: Attack for a single student, then do for an array of N
// students.

//Grading Program
//Policies:
//
// Two quizzes, 10 points each
// midterm and final exam, 100 points each
// Of grade, final counts 50%, midterm 25%, quizes25%
//
// Letter Grade is assigned:

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

// 90 or more A
// 80 or more B
// 70 or more C
// 60 or more D
// less than 60, F
//
// Read a student's scores,
// output record: scores + numeric average + assigned letter grade
//
// Use a struct to contain student record.

struct StudentRecord
{
int studentNumber;
double quiz1;
double quiz2;
double midterm;
double final;
double average;
char grade;
};

//prompts for input for one student, sets the


//structure variable members.
void input(StudentRecord& student);

//calculates the numeric average and letter grade.


void computeGrade(StudentRecord& student);

//outputs the student record.


void output(const StudentRecord student);

int main()
{
StudentRecord student[CLASS_SIZE];

for(int i = 0; i < CLASS_SIZE; i++)


input(student[i]);

// Enclosing block fixes VC++ "for" loop control defined outside loop
{ for(int i = 0; i < CLASS_SIZE; i++)
{
computeGrade(student[i]);
output(student[i]);
cout << endl;
}
}
return 0;
}

void input(StudentRecord &student)


{
cout << "enter the student number: ";
cin >> student.studentNumber;
cout << student.studentNumber << endl;
cout << "enter two 10 point quizes" << endl;
cin >> student.quiz1 >> student.quiz2;

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

cout << student.quiz1 << " " << student.quiz2 << endl;
cout << "enter the midterm and final exam grades."
<< "These are 100 point tests\n";
cin >> student.midterm >> student.final;
cout << student.midterm << " " << student.final
<< endl << endl;
}

void computeGrade(StudentRecord& student)


{
// Of grade, final counts 50%, midterm 25%, quizes25%

double quizAvg= (student.quiz1 + student.quiz2)/2.0;


double quizAvgNormalized = quizAvg * 10;

student.average = student.final * 0.5 +


student.midterm * 0.25 +
quizAvgNormalized * 0.25;
char letterGrade[]= "FFFFFFDCBAA";
int index = static_cast<int>(student.average/10);
if(index < 0 || 10 <= index)
{
cout << "Bad numeric grade encountered: "
<< student.average << endl
<< " Aborting.\n";
abort();
}
student.grade = letterGrade[index];
}

void output(const StudentRecord student)


{
cout << "The record for student number: "
<< student.studentNumber << endl
<< "The quiz grades are: "
<< student.quiz1 << " " << student.quiz2
<< endl
<< "The midterm and exam grades are: "
<< student.midterm << " " << student.final
<< endl
<< "The numeric average is: " << student.average
<< endl
<< "and the letter grade assigned is "
<< student.grade
<< endl;
}

Data for the test run:


1 7 10 90 95
2 9 8 90 80
3 7 8 70 80
4 5 8 50 70
5 4 0 40 35

Command line command to execute the text run:

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

ch6prg1 < data

Output:

enter the student number: 1


enter two 10 point quizes
7 10
enter the midterm and final exam grades. These are 100 point tests
90 95

enter the student number: 2


enter two 10 point quizes
9 8
enter the midterm and final exam grades. These are 100 point tests
90 80

enter the student number: 3


enter two 10 point quizes
7 8
enter the midterm and final exam grades. These are 100 point tests
70 80

enter the student number: 4


enter two 10 point quizes
5 8
enter the midterm and final exam grades. These are 100 point tests
50 70

enter the student number: 5


enter two 10 point quizes
4 0
enter the midterm and final exam grades. These are 100 point tests
40 35

The record for student number: 1


The quiz grades are: 7 10
The midterm and exam grades are: 90 95
The numeric average is: 91.25
and the letter grade assigned is A

The record for student number: 2


The quiz grades are: 9 8
The midterm and exam grades are: 90 80
The numeric average is: 83.75
and the letter grade assigned is B

The record for student number: 3


The quiz grades are: 7 8
The midterm and exam grades are: 70 80
The numeric average is: 76.25
and the letter grade assigned is C

The record for student number: 4


The quiz grades are: 5 8
The midterm and exam grades are: 50 70
The numeric average is: 63.75
and the letter grade assigned is D

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

The record for student number: 5


The quiz grades are: 4 0
The midterm and exam grades are: 40 35
The numeric average is: 32.5
and the letter grade assigned is F
*/

2. CounterType
An object of CounterType is used to count things, so it records a count that is a nonnegative
integer number. It has mutators to increment by 1 and decrement by 1, but no member allows the
counter value to go negative.

There is an accessor that returns the count value, and a display function that displays the count
value on the screen.

Apropos of confusing error messages, this one is worth comment. In compiling the code for this
problem, the following warning message was generated from VC++6.0 on the last line of the
following code fragment:
warning: integral size mismatch in argument; conversion supplied
cout << "starting at counter value "
<< localCounter.currentCount
<< "and decrementing "
<< MAX << " times only decrements to zero.\n\n";
If the error message had been on the offending line, it would have been trivial to see the missing
parentheses on the second line of this code fragment. Warn the students that the error message
may be given several lines after the offending bit of code.

//Ch6prg2.cpp
//CounterType
//
// The class keeps a non-negative integer value.
// It has 2 mutators one increments by 1 and
// the other decrements by 1.
// No member function is allowed to drive the value of the counter
// to become negative. (How to do this is not specified.)
// It has an accessor that returns the count value,
// and a display member that write the current count value
// to the screen.

#include <iostream>
using namespace std;

const int MAX = 20;

class CounterType
{
public:
void InitializeCounter();
void increment();

//ignore request to decrement if count is zero

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

void decrement();

int currentCount();
void display();
private:
int count;
};

int main()
{

CounterType localCounter;

localCounter.InitializeCounter();

{
for(int i = 1; i < MAX; i++)
if(i%3 == 0) // true when i is divisible by 3
localCounter.increment();
}

cout << "There are " << localCounter.currentCount()


<< " numbers between 1 and " << MAX << " that are divisible by 3.\n\n";

cout << "Starting at counter value "


<< localCounter.currentCount(
<< " and decrementing "
<< MAX << " times only decrements to zero.\n\n";

{
for(int i = 1; i < MAX; i++)
{
localCounter.display();
cout << " ";
localCounter.decrement();
}
}
cout << endl << endl;
return 0;

void CounterType::InitializeCounter()
{
count = 0;
}

void CounterType::increment()
{
count++;
}
void CounterType::decrement()
{
if(count > 0) count--;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

void CounterType::display()
{
cout << count;
}

int CounterType::currentCount()
{
return count;
}

A run gives this output:


There are 6 numbers between
1 and 20 that are divisible by 3.

Starting at counter value 6 and decrementing 20


times only decrements to zero.

6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0

3. A Point class
A point in the plane requires two coordinates. We could choose from many coordinate systems.
The two that are most familiar are rectangular and polar. We choose rectangular coordinates (two
double values representing distances from the point in question to perpendicular coordinates).
Conversion the internal representation of this class from rectangular to polar coordinates
should be an excellent problem for students who are reasonably prepared.
These members should be implemented:
a) a member function, set, to set the private data after creation
b) a member function to move the point a vertical distance and a horizontal distance
specified by the first and second arguments.
c) a member function that rotates the point 90 degrees clockwise about the origin.
d) two const inspector functions to retrieve the current coordinates of the point.
Document the member functions.
Test with several points exercise member functions.

//Ch6prg3.cpp

#include <iostream>
using namespace std;

// Point
// The members should implement
// a)a member function, set, to set the private data after creation
// b)a member function to move the point a vertical distance and a
// horizontal distance specified by the first and second arguments.
// c)a member function that rotates the point 90 degrees clockwise
// about the origin.
// d)two const inspector functions to retrieve the current coordinates
// of the point.
// Document the member functions.
// Test with several points exercise member functions.

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

class Point
{
public:
//set: set x to first, y to second
void set(int first, int second);

//move point horizontally by distance first


//move vertically by distance second
void move(int first, int second);

//rotate point 90 degrees clockwise


void rotate();

// returns the first coordinate of the point


double first();
// returns the second coordinate of the point
double second();
private:
double x;
double y;
};

double Point::first()
{
return x;
}

double Point::second()
{
return y;
}

void Point::set(int first, int second)


{
x = first;
y = second;
}

void Point::move(int first, int second)


{
x = x + first;
y = y + second;
}

void Point::rotate()
{
double tmp = x;
x = -y;
y = tmp;
}

int main()
{
Point A, B, C;
A.set(1,2);
cout << A.first() << ", " << A.second() << endl;

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;
A.rotate();
cout << A.first() << ", " << A.second() << endl;

B.set(2,3);
cout << B.first() << ", " << B.second() << endl;
B.move(1,1);
cout << B.first() << ", " << B.second() << endl;

C.set(5, -4);
cout << C.first() << ", " << C.second() << endl;
cout << "Move C by -5 horizontally and 4 vertically. " << endl;
C.move(-5, 4);
cout << C.first() << ", " << C.second() << endl;

return 0;
}

In this execution of the program: We start with (1,2). This point is rotated 90 degrees, four times,
getting back to the original point. The point (3,4) is set and moved by (1,1), that is, one up, one
right). A second point, (5,-4) is set and moved by (-5,4) one left, on down. Then we move it back
to the origin, (0,0). The output from this run is:
1, 2
-2, 1
-1, -2
2, -1
1, 2
-2, 1
2, 3
3, 4
5, -4
Move C by -5 horizontally and 4 vertically.
0, 0

4. A Gas Pump Simulation


The model should have member functions that
a)
display the amount dispensed
b)
display the amount charged for the amount dispensed
c)
display the cost per gallon
d)
reset amount dispensed and amount charged to 0 prior to dispensing
e)
dispense fuel. Once started the gas pump continues to dispense fuel, continually keeping
track of both amount of money charged and amount of fuel dispensed until stopped.
f) a control to stop dispensing.
The implementation was carried out as follows:

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

1) Implement a class definition that models of the behavior of the gas pump.
2) Write implementations of the member functions.
3) Decide whether there are other data the pump must keep track of that the user should not
have access to.

Parts a) b) c) d) are straightforward to implement. Part e), the pumping operation is a little tricky.
Once I realized that the valve on the nozzle must be held to continue to dispense gas, I decided to
model that behavior by repeatedly pressing <CR> is an easy step. Tweaking the appearance and
behavior detail is all that was left. The tweaking was not trivial.
There are notes in the GasPump class definition that are addressed to the instructor. These
concern members that should be declared static or should have been members of a manager class
that is a friend of this class. The student is not likely to understand these notes. I suggest that you
delete these remarks if you give this solution to the student.
#include <iostream>
using namespace std;

class GasPump
{
public:
void initialize(); // set charges, amount dispensed, and
//gasInMainTank to 0.
void reset(); // set charges and amount dispensed to 0;
void displayCostPerGallon();
//If there is only one grade, of gasoline, this should be a static
//member of GasPump, since it would then apply to all instances of
//GasPump. If there are several grades, then this and costPerGallon
//should be ordinary members.

void displayGasNCharges();
// Dispense member continually updates display of new amount and
// new charges
void dispense();
void stop(); // If called, stops dispensing operation.
// My implementation never used this.

private:
double gasDispensed;
double charge;

public:
//Perhaps these functions should be static members of this class.
//See the earlier comment about this.
void setPricePerGallon(double newPrice);
void buyFromJobber(double quantity);
void displayAmountInMainTank();

private:
//These variables should be static members, since
//they are associated with all class instances.

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

double gasInMainTank;
double costPerGallon;
};

void GasPump::displayAmountInMainTank()
{
cout << gasInMainTank;
}

void GasPump::setPricePerGallon(double newPrice)


{
costPerGallon = newPrice;
}

void GasPump::buyFromJobber(double quantityBought)


{
gasInMainTank += quantityBought;
}

void GasPump::initialize()
{
gasDispensed = 0;
charge = 0;
gasInMainTank = 0;
}

void GasPump::reset()
{
gasDispensed = 0;
charge = 0;
}

void GasPump::displayCostPerGallon()
{
cout << costPerGallon;
}

void GasPump::displayGasNCharges()
{
cout << "gallons: " << gasDispensed
<< " $" << charge << endl;
}

void GasPump::dispense()
{
char quit;

system("cls"); // Windows clear screen


//system("clear"); // Unix/Linux

cout << "\n\nDISPENSING FUEL\n";


displayGasNCharges();
cout << "\nPress <CR> to dispense in 0.1 gallon increments. "
<< "\nPress q or Q <CR>to terminate dispensing.\n";

while(gasInMainTank > 0)
{

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

quit = cin.get();
if (quit == 'q' || quit == 'Q')
break;

charge += 0.1 * costPerGallon;


gasDispensed += 0.1;
gasInMainTank -= 0.1;

system("cls"); // Windows clear screen


//system("clear"); // Unix/Linux

cout << "\n\nDISPENSING FUEL\n";


displayGasNCharges();
cout << "\nPress <CR> to dispense in 0.1 gallon increments. "
<< "\nPress q or Q <CR>to terminate dispensing.\n";
}
if(0 == gasInMainTank)
cout << "Dispensing ceased because main tank is empty.\n";
}

int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

GasPump pump;
char ans;

cout << "Gas Pump Modeling Program\n";

pump.initialize();
pump.setPricePerGallon(1.50);
pump.buyFromJobber(25);
cout << "Amount of gasoline in main tank is: ";
pump.displayAmountInMainTank();
cout << endl;

cout << "Gasoline price is $";


pump.displayCostPerGallon();
cout << " per gallon.\n";

pump.displayGasNCharges();

cout << "Press Y/y <CR> to run the dispensing model,"


<< " anything else quits. \n";
cin >> ans;
if( !('Y' == ans || 'y' == ans) )
return 0;

system("cls"); // Windows
//system("clear"); // Unix/Linux

cout << "\nWelcome Customer #1\n";


cout << "Press Y/y <CR> to start dispensing Fuel,”
<< “ other quits \n";
cin >> ans;

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

if('Y'==ans || 'y' == ans)


{
ans = cin.get(); // eat <cr>
pump.dispense();
}
cout << "Thank you. Your charges are:\n" ;
pump.displayGasNCharges();
cout << endl;

cout << "\n\nAmount of gasoline remaining in main tank is: ";


pump.displayAmountInMainTank();
cout << " gallons\n";

cout << "\n\nWelcome Customer #2\n";


pump.displayGasNCharges();

cout << "Press Y/y <CR> to start dispensing Fuel,"


<< " anything else quits dispensing. \n";
cin >> ans;
if('Y'==ans || 'y' == ans)
{
pump.reset(); // zero old charges
ans = cin.get(); // eat <cr>
pump.dispense();
}
cout << "Thank you. Your charges are:\n" ;
pump.displayGasNCharges();
cout << endl;

cout << "\n\nAmount of gasoline remaining in main tank is: ";


pump.displayAmountInMainTank();
cout << " gallons\n";

return 0;
}

5. Fraction
Define a class for a type called Fraction. This class is used to represent a ratio of two integers.
Include mutator functions that allow the user to set the numerator and the denominator. Also
include a member function that returns the value of numerator / denominator as a double. Include
an additional member function that outputs the value of the fraction reduced to lowest terms, e.g.
instead of outputting 20/60 the method should output 1/3. This will require finding the greatest
common divisor for the numerator and denominator, and then dividing both by that number.
Embed your class in a test program.

//fraction.cpp
//This program defines a class for fractions, which stores a numerator
// and denominator. A member functions allows for retrieval of the
// fraction as a double and another outputs the value in lowest
// terms.

//The greatest common divisor is found to reduce the fraction.


// In this case we use a brute-force method to find the gcd, but

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

// a more efficient solution such as euclid's method could also be


// used.

#include <iostream>
#include <cstdlib>

using namespace std;

class Fraction
{
public:
double getDouble();
void outputReducedFraction();
void setNumerator(int n);
void setDenominator(int d);

private:
int numerator;
int denominator;
int gcd(); // Finds greatest common divisor of numerator
// and denominator
};

// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------

// ======================
// Fraction::getDouble
// Returns the fraction's value as a double
// ======================
double Fraction::getDouble()
{
return (static_cast<double>(numerator) / denominator);
}

// ======================
// Fraction::outputReducedFraction
// Reduces the fraction and outputs it to the console.
// ======================
void Fraction::outputReducedFraction()
{
int g;

g = gcd();
cout << numerator / g << " / " << denominator / g << endl;
return;
}

// ======================
// Fraction::setNumerator
// Mutator to change the numerator
// ======================
void Fraction::setNumerator(int n)
{
numerator = n;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

// ======================
// Fraction::setDenominator
// Mutator to change the denominator
// ======================
void Fraction::setDenominator(int d)
{
denominator = d;
}

// ======================
// Fraction::gcd
// Finds greatest common divisor of numerator and denominator
// by brute force (start at larger of two, work way down to 1)
// ======================
int Fraction::gcd()
{
int g; // candidate for gcd, start at the smaller of the
// numerator and denominator

if (numerator > denominator)


{
g = denominator;
}
else
{
g = numerator;
}

// Work down to 1, testing to see if both numerator and denominator


// can be divided by g. If so, return it.
while (g>1)
{
if (((numerator % g)==0) && ((denominator % g)==0))
return g;
g--;
}
return 1;
}

// --------------------------------
// --------- END USER CODE --------
// --------------------------------

// ======================
// main function
// ======================
int main()
{
// Some test fractions
Fraction f1, f2;

f1.setNumerator(4);
f1.setDenominator(2);
cout << f1.getDouble() << endl;
f1.outputReducedFraction();

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

cout << endl;


f2.setNumerator(20);
f2.setDenominator(60);
cout << f2.getDouble() << endl;
f2.outputReducedFraction();
cout << endl;

6. Odometer
Define a class called Odometer that will be used to track fuel and mileage for an automotive
vehicle. The class should have member variables to track the miles driven and the fuel efficiency
of the vehicle in miles per gallon. Include a mutator function to reset the odometer to zero miles,
a mutator function to set the fuel efficiency, a mutator function that accepts miles driven for a trip
and adds it to the odometer’s total, and an accessor method that returns the number of gallons of
gasoline that the vehicle has consumed since the odometer was last reset.

Use your class with a test program that creates several trips with different fuel efficiencies. You
should decide which variables should be public, if any.

//odometer.cpp
//This program defines an Odometer class to track fuel and mileage.
// It stores the miles driven and fuel efficient and includes
// a function to calculate the number of gallons of gasoline consumed.

#include <iostream>
#include <cstdlib>

using namespace std;

class Odometer
{
public:
void setFuelEfficiency(double newEfficiency);
void reset();
void logMiles(int additionalMiles);
double gasConsumed();

private:
int miles;
double fuel_efficiency;
};

// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------

// ======================
// Odometer::setFuelEfficiency
// Sets the fuel efficiency in miles per gallon.
// ======================

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

void Odometer::setFuelEfficiency(double newEfficiency)


{
fuel_efficiency = newEfficiency;
}

// ======================
// Odometer::reset
// Resets the odometer reading
// ======================
void Odometer::reset()
{
miles = 0;
}

// ======================
// Odometer::addMiles
// Log additional miles to the odometer.
// ======================
void Odometer::logMiles(int additionalMiles)
{
miles += additionalMiles;
}

// ======================
// Odometer::gasConsumed
// Calculates the gallons of gas consumed on the trip.
// ======================
double Odometer::gasConsumed()
{
return (miles / fuel_efficiency);
}

// --------------------------------
// --------- END USER CODE --------
// --------------------------------

// ======================
// main function
// ======================
int main()
{
// Two test trips
Odometer trip1, trip2;

void setFuelEfficiency(double newEfficiency);


void reset();
void logMiles(int additionalMiles);
double gasConsumed();

trip1.reset();
trip1.setFuelEfficiency(45);
trip1.logMiles(100);
cout << "For your fuel-efficient small car:" << endl;
cout << "After 100 miles, " << trip1.gasConsumed() <<
" gallons used." << endl;
trip1.logMiles(50);

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

cout << "After another 50 miles, " << trip1.gasConsumed() <<


" gallons used." << endl;

cout << endl;


trip2.reset();
trip2.setFuelEfficiency(13);
trip2.logMiles(100);
cout << "For your gas guzzler:" << endl;
cout << "After 100 miles, " << trip2.gasConsumed() <<
" gallons used." << endl;
trip2.logMiles(50);
cout << "After another 50 miles, " << trip2.gasConsumed() <<
" gallons used." << endl;
}

7. Pizza
Define a class called Pizza that has member variables to track the type of pizza (either deep
dish, hand tossed, or pan) along with the size (either small, medium, or large) and the number of
pepperoni or cheese toppings. You can use constants to represent the type and size. Include
mutator and accessor functions for your class. Create a void function, outputDescription( ),
that outputs a textual description of the pizza object. Also include a function, computePrice( ),
that computes the cost of the pizza and returns it as a double according to the rules:

Small pizza = $10 + $2 per topping


Medium pizza = $14 + $2 per topping
Large pizza = $17 + $2 per topping

Write a suitable test program that creates and outputs a description and price of various pizza
objects.

Notes: You may wish to point out that this could be better organized using inheritance and
classes for each type of pizza.
// pizza.h
//
// Interface file for the Pizza class.

const int SMALL = 0;


const int MEDIUM = 1;
const int LARGE = 2;

const int DEEPDISH = 0;


const int HANDTOSSED = 1;
const int PAN = 2;

class Pizza
{
public:
Pizza();
~Pizza() {};
int getPepperoniToppings();
void setPepperoniToppings(int numPepperoni);

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

int getCheeseToppings();
void setCheeseToppings(int numCheese);
int getSize();
void setSize(int newSize);
int getType();
void setType(int newType);
void outputDescription();
double computePrice();
private:
int size, type, pepperoniToppings, cheeseToppings;
};

// pizza.cpp
//
// This program implements the Pizza class and creates several
// pizza objects to test it out.

#include <iostream>
#include "pizza.h"

using namespace std;

//========================
// Pizza
// The constructor sets the default pizza
// to a small, deep dish, with only cheese.
//========================
Pizza::Pizza()
{
size = SMALL;
type = DEEPDISH;
pepperoniToppings = 0;
cheeseToppings = 1;
}

//==================================
// Accessors and Mutators Follow
//==================================

// --------------------------------
// ----- ENTER YOUR CODE HERE -----
// --------------------------------

int Pizza::getPepperoniToppings()
{
return pepperoniToppings;
}

void Pizza::setPepperoniToppings(int numPepperoni)


{
pepperoniToppings = numPepperoni;
}

int Pizza::getCheeseToppings()
{
return cheeseToppings;

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

void Pizza::setCheeseToppings(int numCheese)


{
cheeseToppings = numCheese;
}

int Pizza::getSize()
{
return size;
}

void Pizza::setSize(int newSize)


{
size = newSize;
}

int Pizza::getType()
{
return size;
}

void Pizza::setType(int newType)


{
type = newType;
}

//==================================
// outputDescription
// Prints a textual description of the contents of the pizza.
//==================================
void Pizza::outputDescription()
{
cout << "This pizza is: ";
switch (size)
{
case SMALL: cout << "Small, ";
break;
case MEDIUM: cout << "Medium, ";
break;
case LARGE: cout << "Large, ";
break;
default: cout << "Unknown size, ";
}
switch (type)
{
case DEEPDISH: cout << "Deep dish, ";
break;
case HANDTOSSED: cout << "Hand tossed, ";
break;
case PAN: cout << "Pan, ";
break;
default: cout << "Uknown type, ";
}
cout << "with " << pepperoniToppings << " pepperoni toppings " <<
"and " << cheeseToppings << " cheese toppings." << endl;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

//==================================
// computePrice
// Returns:
// Price of a pizza using the formula:
// Small = $10 + $2 per topping
// Medium = $14 + $2 per topping
// Large = $17 + $2 per topping
//==================================
double Pizza::computePrice()
{
double price = 0;
switch (size)
{
case SMALL: price = 10; break;
case MEDIUM: price = 14; break;
case LARGE: price = 17; break;
default: cout << "Error, invalid size." << endl;
return -1;
}
price += (pepperoniToppings + cheeseToppings) * 2;
return price;
}

// --------------------------------
// --------- END USER CODE --------
// --------------------------------

// ======================
// main function
// ======================
int main()
{

// Variable declarations
Pizza cheesy;
Pizza pepperoni;

cheesy.setCheeseToppings(3);
cheesy.setType(HANDTOSSED);
cheesy.outputDescription();
cout << "Price of cheesy: " << cheesy.computePrice() << endl;

pepperoni.setSize(LARGE);
pepperoni.setPepperoniToppings(2);
pepperoni.setType(PAN);
pepperoni.outputDescription();
cout << "Price of pepperoni : " << pepperoni.computePrice() << endl;
cout << endl;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

8. Money
Define a class named Money that stores a monetary amount. The class should have two private
integer variables, one to store the number of dollars and another to store the number of cents.
Add accessor and mutator functions to read and set both member variables. Add another
function that returns the monetary amount as a double. Write a program that tests all of your
functions with at least two different Money objects.
#include <iostream>
using namespace std;

class Money
{
public:
int getDollars();
int getCents();
void setDollars(int d);
void setCents(int c);
double getAmount();
private:
int dollars;
int cents;
};

int Money::getDollars()
{
return dollars;
}

int Money::getCents()
{
return cents;
}

void Money::setDollars(int d)
{
dollars = d;
}

void Money::setCents(int c)
{
cents = c;
}

double Money::getAmount()
{
return static_cast<double>(dollars) +
static_cast<double>(cents) / 100;
}

int main( )
{
Money m1, m2;
m1.setDollars(20);
m1.setCents(35);
m2.setDollars(0);

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

m2.setCents(98);

cout << m1.getDollars() << "." << m1.getCents() << endl;


cout << m1.getAmount() << endl;
cout << m2.getAmount() << endl;

cout << "Changing m1's dollars to 50" << endl;


m1.setDollars(50);
cout << m1.getAmount() << endl;

cout << "Enter a character to exit." << endl;


char wait;
cin >> wait;
return 0;
}

9. Money Data Hiding


Do Programming Project 6.8 except remove the two private integer variables and in their place
use a single variable of type double to store the monetary value. The rest of the functions
should have the same headers. For several functions this will require code to convert from an
integer format to appropriately modify the double. For example, if the monetary amount stored
in the double is 4.55 (representing $4.55) then if the function to set the dollar amount is invoked
with the value 13, then the double should be changed to 13.55. While this will take some work,
the code in your test program from Programming Project 6.8 should still work without requiring
any changes. This is the benefit of encapsulating the member variables.

#include <iostream>
using namespace std;

class Money
{
public:
int getDollars();
int getCents();
void setDollars(int d);
void setCents(int c);
double getAmount();
private:
//int dollars, cents; // In OLD version
double amount;
};

int Money::getDollars()
{
// return dollars
return static_cast<int>(amount);
}

int Money::getCents()
{
//return cents;
int val = static_cast<int>(amount * 100);
if (val > 0)
return val % 100;

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

// The following logic handles negative amounts


else if ((val < 0) && (val > -1))
// Negative cents (no neg dollars)
return val % 100;
else
// No neg cents (neg dollars)
return -1 * (val % 100);
}

void Money::setDollars(int d)
{
int pennies = getCents(); // Current cents
amount = static_cast<double>(d) + (pennies / 100.0);
//dollars = d;
}

void Money::setCents(int c)
{
amount = static_cast<double>(getDollars()) +
(c / 100.0);
//cents = c;
}

double Money::getAmount()
{
//return static_cast<double>(dollars) +
// static_cast<double>(cents) / 100;
return amount;
}

// This main function is identical to the PP 6.8


int main( )
{
Money m1, m2;
m1.setDollars(20);
m1.setCents(35);
m2.setDollars(0);
m2.setCents(98);

cout << m1.getDollars() << "." << m1.getCents() << endl;


cout << m1.getAmount() << endl;
cout << m2.getAmount() << endl;

cout << "Changing m1's dollars to 50" << endl;


m1.setDollars(50);
cout << m1.getAmount() << endl;

cout << "Enter a character to exit." << endl;


char wait;
cin >> wait;
return 0;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

10. Temperature Class


Create a Temperature class that internally stores a temperature in degrees Kelvin. However,
create functions named setTempKelvin, setTempFahrenheit, and setTempCelsius
that takes an input temperature in the specified temperature scale, converts the temperature to
Kelvin, and stores that temperature in the class member variable. Also create functions that
return the stored temperature in degrees Kelvin, Fahrenheit, or Celsius. Write a main function to
test your class. Use the equations below to convert between the three temperature scales.
Kelvin = Celsius + 273.15
Celsius = (5/9) X (Fahrenheit - 32)

#include <iostream>
using namespace std;

class Temperature
{
public:
void setTempKelvin(double temp);
void setTempFahrenheit(double temp);
void setTempCelsius(double temp);
double getTempKelvin();
double getTempFahrenheit();
double getTempCelsius();
private:
double kelvin; // Internally store temp in kelvin
};

void Temperature::setTempKelvin(double temp)


{
kelvin = temp;

void Temperature::setTempFahrenheit(double temp)


{
kelvin = (5.0 * (temp - 32) / 9) + 273.15;
}

void Temperature::setTempCelsius(double temp)


{
kelvin = temp + 273.15;
}

double Temperature::getTempKelvin()
{
return kelvin;
}

double Temperature::getTempCelsius()
{
return kelvin - 273.15;
}

double Temperature::getTempFahrenheit()
{

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

return (getTempCelsius() * 9.0 / 5) + 32;


}

int main( )
{
Temperature temp;
temp.setTempFahrenheit(32);
cout << "In Celsius: " << temp.getTempCelsius() << endl;
cout << "In Fahrenheit: " << temp.getTempFahrenheit() << endl;
cout << "In Kelvin: " << temp.getTempKelvin() << endl;
cout << endl;

temp.setTempCelsius(100);
cout << "In Celsius: " << temp.getTempCelsius() << endl;
cout << "In Fahrenheit: " << temp.getTempFahrenheit() << endl;
cout << "In Kelvin: " << temp.getTempKelvin() << endl;
cout << endl;

temp.setTempKelvin(0);
cout << "In Celsius: " << temp.getTempCelsius() << endl;
cout << "In Fahrenheit: " << temp.getTempFahrenheit() << endl;
cout << "In Kelvin: " << temp.getTempKelvin() << endl;
cout << endl;

cout << "Enter a character to exit." << endl;


char wait;
cin >> wait;
return 0;
}

11. High Scores

Do Programming Project 5.18 except use only one array as a parameter instead of two arrays.
The single array should be of type Player where Player is a class that you create. The
Player class should have a member variable of type string to store the player's name and a
member variable of type int to score the player's score. Encapsulate these variables
appropriately. When your function returns the array entry at index 0 should be set to the name
and score of the player with the top score, the entry at index 1 should be set to the name and
score of the player with the second best score, etc.

This solution is a conversion of PP 5.18.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class Player
{
public:
void setName(string newname);
void setScore(int newscore);

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

string getName();
int getScore();
private:
string name;
int score;
};

void Player::setName(string newname)


{
name = newname;
}
void Player::setScore(int newscore)
{
score = newscore;
}
string Player::getName()
{
return name;
}
int Player::getScore()
{
return score;
}

void getHighScores(Player players[]);


void sort(Player players[], int numberUsed);
void swapValues(Player& v1, Player& v2);
int indexOfLargest(Player players[], int startIndex, int numberUsed);

int main( )
{
Player players[100];
getHighScores(players);

// Output the top 3


for (int i = 0; i < 3; i++)
{
cout << players[i].getName() <<
" " << players[i].getScore() << endl;
}

return 0;
}

// Assumes that the array is large enough to


// hold the input data.
void getHighScores(Player players[])
{
int numScores = 0;

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

string curname;
int curscore;
fstream inputStream;

inputStream.open("scores.txt");
while (inputStream >> curname)
{
inputStream >> curscore;
players[numScores].setScore(curscore);
players[numScores].setName(curname);
numScores++;
}
sort(players, numScores);
}

void sort(Player players[], int numberUsed)


{
int indexOfNextLargest;
for (int index = 0; index < numberUsed - 1; index++)
{
indexOfNextLargest =
indexOfLargest(players, index, numberUsed);
swapValues(players[index], players[indexOfNextLargest]);
}
}

void swapValues(Player& v1, Player& v2)


{
Player temp;
temp = v1;
v1 = v2;
v2 = temp;
}

int indexOfLargest(Player players[], int startIndex, int numberUsed)


{
int max = players[startIndex].getScore(),
indexOfMax = startIndex;
for (int index = startIndex + 1; index < numberUsed; index++)
if (players[index].getScore() > max)
{
max = players[index].getScore();
indexOfMax = index;
}

return indexOfMax;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

12. Box of Produce

Your Community Supported Agriculture (CSA) farm delivers a box of fresh fruits and
vegetables to your house once a week. For this Programming Project, define the class
BoxOfProduce that contains exactly three bundles of fruits or vegetables. You can represent
the fruits or vegetables as an array of type string. Add accessor and mutator functions to get
or set the fruits or vegetables stored in the array. Also write an output function that displays
the complete contents of the box on the console.

Next write a main function that creates a BoxOfProduce with three items randomly selected
from this list:
Broccoli
Tomato
Kiwi
Kale
Tomatillo

This list should be stored in a text file that is read in by your program. For now you can assume
that the list contains exactly five types of fruits or vegetables.
Don't worry if your program randomly selects duplicate produce for the three items. Next, the
main function should display the contents of the box and allow the user to substitute any one of
the five possible fruits or vegetables for any of the fruits or vegetables selected for the box.
After the user is done with substitutions output the final contents of the box to be delivered.

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

// Max number of bundles in a box


const int MAX_BUNDLES = 100;

class BoxOfProduce
{
private:
int numBundles;
string bundle[MAX_BUNDLES];
public:
void initialize();
void addBundle(string b);
string getBundle(int index);
void setBundle(string b, int index);
string boxContents();
};

// This is better done in a constructor but


// that topic has not been covered yet
void BoxOfProduce::initialize()

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

{
numBundles = 0;
}

void BoxOfProduce::addBundle(string b)
{
if (numBundles < MAX_BUNDLES)
{
bundle[numBundles] = b;
numBundles++;
}
}

string BoxOfProduce::getBundle(int index)


{
if ((index >=0) && (index < MAX_BUNDLES))
return bundle[index];
else
return "";
}

void BoxOfProduce::setBundle(string b, int index)


{
if ((index >=0) && (index < MAX_BUNDLES))
bundle[index] = b;
}

// '0'+i+1 converted to a char is an ASCII digit, converted to a string


// stringstream is another way to convert an int to a string
string BoxOfProduce::boxContents()
{
string s = "The box contains: ";
for (int i = 0; i < numBundles; i++)
s = s + " (" + char('0'+i+1) + ")" + bundle[i];
return s;
}

int main()
{
// Create a Box
BoxOfProduce box;
box.initialize();

// Initialize the random number generator


srand(time(NULL));
// Pick three random numbers from 0 to 4 for the 5 possible food
choices
int num1, num2, num3;
num1 = rand() % 5;
num2 = rand() % 5;
num3 = rand() % 5;

int lineRead = 0;
ifstream inputStream;
inputStream.open("produce.txt");

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

string food;
while (inputStream >> food)
{
if (lineRead == num1)
box.addBundle(food);
if (lineRead == num2)
box.addBundle(food);
if (lineRead == num3)
box.addBundle(food);
lineRead++;
}
inputStream.close();

// Show the box contents to the user and allow substitutions


char selection = ' ';
do
{
cout << box.boxContents() << endl;
cout << "Enter 'a' to add a new bundle." << endl;
cout << "Enter 'c' to change a bundle." << endl;
cout << "Enter 'q' to quit." << endl;
cin >> selection;
if (selection == 'a')
{
cout << "Enter item to add." << endl;
string item;
cin >> item;
box.addBundle(item);
}
else if (selection == 'c')
{
cout << "Enter index of item to change." << endl;
int i;
cin >> i;
cout << "Enter item to substitute." << endl;
string item;
cin >> item;
box.setBundle(item, i-1); // Index is 0 based so sub 1
}
} while (selection != 'q');
cout << "Final Contents:" << endl;
cout << box.boxContents() << endl;
return 0;
}

13. High Scores

Do Programming Project 5.19 except use a class named Player to store a player’s name and
score. Then, use an array of the Player class to store the 10 players.

#include <iostream>
#include <string>
using namespace std;

class Player
{

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

private:
string name;
int score;
public:
void setName(string newName);
void setScore(int newScore);
string getName();
int getScore();
};

void Player::setName(string newName)


{
name = newName;
}
void Player::setScore(int newScore)
{
score = newScore;
}
string Player::getName()
{
return name;
}
int Player::getScore()
{
return score;
}

// Prototypes
void addPlayer(int &numPlayers, Player players[]);
void printPlayers(int numPlayers, Player players[]);
void searchPlayers(int numPlayers, Player players[]);
void removePlayer(int &numPlayers, Player players[]);

// Add a new player, max of 10 players


void addPlayer(int &numPlayers, Player players[])
{
if (numPlayers == 10)
cout << "Player array full." << endl;
else
{
cout << "Enter new player name." << endl;
string name;
cin >> name;
players[numPlayers].setName(name);
cout << "Enter new player score." << endl;
int score;
cin >> score;
players[numPlayers].setScore(score);
numPlayers++;
}
}

void printPlayers(int numPlayers, Player players[])


{
cout << "Player Scores" << endl;
for (int i = 0; i < numPlayers; i++)

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

cout << players[i].getName() << " " << players[i].getScore() << endl;
}

void searchPlayers(int numPlayers, Player players[])


{
int index = -1;
string target;

cout << "What player to search for? " << endl;


cin >> target;
for (int i = 0; i < numPlayers; i++)
if (players[i].getName() == target)
index = i;
if (index >= 0)
cout << "The score for " << target << " is "
<< players[index].getScore() << endl;
else
cout << "Player " << target << " not found." << endl;
}

void removePlayer(int &numPlayers, Player players[])


{
int index = -1;
string target;

cout << "What player to remove?" << endl;


cin >> target;
for (int i = 0; i < numPlayers; i++)
if (players[i].getName() == target)
index = i;
if (index >= 0)
{
// Remove the player by swapping the player in the end
// to the [index] of the player to remove.
if (numPlayers-1 != index)
{
players[index] = players[numPlayers - 1];
}
cout << " Player " << target << " removed." << endl;
numPlayers--;
}
else
cout << "Player " << target << " not found." << endl;
}

int main()
{
char option;
Player players[10];
int numPlayers=0;

// Initialize arrays
for (int i =0; i < 10; i++)
{
players[i].setScore(0);
players[i].setName("");

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.


Savitch, Absolute C++ 6/e: Chapter 6, Instructor’s Manual

do
{
cout << "Enter an option." << endl;
cout << "a. Add new player and score." << endl;
cout << "b. Print all players and scores." << endl;
cout << "c. Search for a player's score." << endl;
cout << "d. Remove a player." << endl;
cout << "e. Quit." << endl;

cin >> option;


cout << endl;
if (option == 'a')
addPlayer(numPlayers, players);
else if (option == 'b')
printPlayers(numPlayers, players);
else if (option == 'c')
searchPlayers(numPlayers, players);
else if (option == 'd')
removePlayer(numPlayers, players);
cout << endl;
} while (option != 'e');

return 0;
}

Copyright © 2016 Pearson Education Addison-Wesley. All rights reserved.

You might also like