Programming Projects require more problem-solving than Practice Programs and can usually be solved many different ways. Visit www.myprogramminglab.com to complete many of these Programming Projects online and get instant feedback.
In Chapter 8 we discussed vectors, which are like arrays that can grow in size. Suppose that vectors were not defined in C++. Define a class called VectorDouble
that is like a class for a vector with base type double
. Your class VectorDouble
will have a private member variable for a dynamic array of double
s. It will also have two member variables of type int
; one called maxCount
for the size of the dynamic array of double
s; and one called count
for the number of array positions currently holding values. (maxCount
is the same as the capacity of a vector; count
is the same as the size of a vector.)
If you attempt to add an element (a value of type double
) to the vector object of the class VectorDouble
and there is no more room, then a new dynamic array with twice the capacity of the old dynamic array is created and the values of the old dynamic array are copied to the new dynamic array.
Your class should have all of the following:
Three constructors: a default constructor that creates a dynamic array for 50 elements, a constructor with one int
argument for the number of elements in the initial dynamic array, and a copy constructor.
A destructor.
A suitable overloading of the assignment operator =
.
A suitable overloading of the equality operator ==
. To be equal, the values of count
and the count
array elements must be equal, but the values of maxCount
need not be equal.
Member functions push_back
, capacity
, size
, reserve
, and resize
that behave the same as the member functions of the same names for vectors.
Two member functions to give your class the same utility as the square brackets: valueAt(i)
, which returns the value of the i
th element in the dynamic array; and changeValueAt(d, i)
, which changes the double
value at the i
th element of the dynamic array to d
. Enforce suitable restrictions on the arguments to valueAt
and changeValueAt
. (Your class will not work with the square brackets. It can be made to work with square brackets, but we have not covered the material which tells you how to do that.)
Define a class for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 1/2, 3/4, 64/2, and so forth are all rational numbers. (By 1/2, etc., we mean the everyday meaning of the fraction, not the integer division this expression would produce in a C++ program.) Represent rational numbers as two values of type int
, one for the numerator and one for the denominator. Call the class Rational
.
Include a constructor with two arguments that can be used to set the member variables of an object to any legitimate values. Also include a constructor that has only a single parameter of type int
; call this single parameter wholeNumber
and define the constructor so that the object will be initialized to the rational number wholeNumber
/1. Also include a default constructor that initializes an object to 0 (that is, to 0/1).
Overload the input and output operators >>
and <<
. Numbers are to be input and output in the form 1/2
, 15/32
, 300/401
, and so forth. Note that the numerator, the denominator, or both may contain a minus sign, so −1/2
, 15/32
, and −300/−401
are also possible inputs. Overload all of the following operators so that they correctly apply to the type Rational
: ==
, <
, <=
, >
, >=
, +
, −
, *
, and /
. Also write a test program to test your class.
(Hints: Two rational numbers
a/b
andc/d
are equal ifa*d
equalsc*b.
Ifb
andd
are positive rational numbers,a/b
is less thanc/d
provideda*d
is less thanc*b
. You should include a function to normalize the values stored so that, after normalization, the denominator is positive and the numerator and denominator are as small as possible. For example, after normalization4/−8
would be represented the same as−1/2
. You should also write a test program to test your class.)
Define a class for complex numbers. A complex number is a number of the form
a + b * i
where, for our purposes, a
and b
are numbers of type double
, and i
is a number that represents the quantity double
. Name the member variables real
and imaginary
. (The variable for the number that is multiplied by i
is the one called imaginary
.) Call the class Complex
.
Include a constructor with two parameters of type double
that can be used to set the member variables of an object to any values. Also include a constructor that has only a single parameter of type double
; call this parameter realPart
and define the constructor so that the object will be initialized to realPart+0*i
. Also include a default constructor that initializes an object to 0
(that is, to 0+0*i
). Overload all of the following operators so that they correctly apply to the type Complex
: ==
, +
, −, *
, >>
, and <<
. You should write a test program to test your class.
(Hints: To add or subtract two complex numbers, you add or subtract the two member variables of type
double
. The product of two complex numbers is given by the following formula:(a + b*i)*(c + d*i) == (a*c – b*d) + (a*d + b*c)*i
In the interface file, you should define a constant i
as follows:
const Complex i(0, 1);
This defined constant i
will be the same as the i
discussed earlier.
delete p;
Enhance the definition of the class StringVar
given in Displays 11.11 and 11.12 by adding all of the following:
Member function copyPiece
, which returns a specified substring; member function oneChar
, which returns a specified single character; and member function setChar
, which changes a specified character
An overloaded version of the ==
operator (note that only the string values have to be equal; the values of maxLength
need not be the same)
An overloaded version of +
that performs concatenation of strings of type StringVar
An overloaded version of the extraction operator >>
that reads one word (as opposed to inputLine
, which reads a whole line)
If you did the section on overloading the assignment operator, then add it as well. Also write a suitable test program and thoroughly test your class definition.
Define a class called Text
whose objects store lists of words. The class Text
will be just like the class StringVar
except that the class Text
will use a dynamic array with base type StringVar
rather than base type char
and will mark the end of the array with a StringVar
object consisting of a single blank, rather than using '\0'
as the end marker. Intuitively, an object of the class Text
represents some text consisting of words separated by blanks. Enforce the restriction that the array elements of type StringVar
contain no blanks (except for the end marker elements of type StringVar
).
Your class Text
will have member functions corresponding to all the member functions of StringVar
. The constructor with an argument of type const char a[]
will initialize the Text
object in the same way as described below for inputLine
. If the C-string argument contains the new-line symbol '\n'
, that is considered an error and ends the program with an error message.
The member function inputLine
will read blank separated strings and store each string in one element of the dynamic array with base type StringVar
. Multiple blank spaces are treated the same as a single blank space. When outputting an object of the class Text
, insert one blank between each value of type StringVar
. You may either assume that no tab symbols are used or you can treat the tab symbols the same as a blank; if this is a class assignment, ask your instructor how you should treat the tab symbol.
Add the enhancements described in Programming Project 6. The overloaded version of the extraction operator >>
will fill only one element of the dynamic array.
Using dynamic arrays, implement a polynomial class with polynomial addition, subtraction, and multiplication.
Discussion: A variable in a polynomial does very little other than act as a placeholder for the coefficients. Hence, the only interesting thing about polynomials is the array of coefficients and the corresponding exponent. Think about the polynomial
x*x*x + x + 1
One simple way to implement the polynomial class is to use an array of
double
s to store the coefficients. The index of the array is the exponent of the corresponding term. Where is the term inx*x
in the previous example? If a term is missing, then it simply has a zero coefficient.There are techniques for representing polynomials of high degree with many missing terms. These use so-called sparse polynomial techniques. Unless you already know these techniques, or learn very quickly, don’t use them.
Provide a default constructor, a copy constructor, and a parameterized constructor that enable an arbitrary polynomial to be constructed. Also supply an overloaded operator =
and a destructor.
Provide these operations:
polynomial +
polynomial
constant +
polynomial
polynomial +
constant
polynomial −
polynomial
constant −
polynomial
polynomial −
constant
polynomial *
polynomial
constant *
polynomial
polynomial *
constant
Supply functions to assign and extract coefficients, indexed by exponent.
Supply a function to evaluate the polynomial at a value of type double
.
You should decide whether to implement these functions as members, friends, or stand-alone functions.
Write a checkbook balancing program. The program will read in the following for all checks that were not cashed as of the last time you balanced your checkbook: the number of each check, the amount of the check, and whether or not it has been cashed. Use an array with a class base type. The class should be a class for a check. There should be three member variables to record the check number, the check amount, and whether or not the check was cashed. The class for a check will have a member variable of type Money
(as defined in Display 19) to record the check amount. So, you will have a class used within a class. The class for a check should have accessor and mutator functions as well as constructors and functions for both input and output of a check.
In addition to the checks, the program also reads all the deposits, as well as the old and the new account balance. You may want another array to hold the deposits. The new account balance should be the old balance plus all deposits, minus all checks that have been cashed.
The program outputs the total of the checks cashed, the total of the deposits, what the new balance should be, and how much this figure differs from what the bank says the new balance is. It also outputs two lists of checks: the checks cashed since the last time you balanced your checkbook and the checks still not cashed. Display both lists of checks in sorted order from lowest to highest check number.
If this is a class assignment, ask your instructor if input/output should be done with the keyboard and screen or if it should be done with files. If it is to be done with files, ask your instructor for instructions on file names.
Define a class called List
that can hold a list of values of type double
. Model your class definition after the class TemperatureList
given in Display 11.10, but your class List
will make no reference to temperatures when it outputs values. The values may represent any sort of data items as long as they are of type double
. Include the additional features specified in Self-Test Exercises 21 and 22. Change the member function names so that they do not refer to temperature.
Add a member function called getLast
that takes no arguments and returns the last item on the list. The member function getLast
does not change the list, and it should not be called if the list is empty. Add another member function called deleteLast
that deletes the last element on the list. The member function deleteLast
is a void
function. Note that when the last element is deleted, the member variable size
must be adjusted. If deleteLast
is called with an empty list as the calling object, the function call has no effect. Design a program to thoroughly test your definition for the class List
.
Define a class called StringSet
that will be used to store a set of STL strings. Use an array or a vector to store the strings. Create a constructor that takes as an input parameter an array of strings for the initial values in the set. Then write member functions to add a string to the set, remove a string from the set, clear the entire set, return the number of strings in the set, and output all strings in the set. Overload the +
operator so that it returns the union of two StringSet
objects. Also overload the *
operator so that it returns the intersection of two StringSet
objects. Write a program to test all member functions and overloaded operators in your class.
This programming project requires you to complete Programming Project 9 first.
The field of information retrieval is concerned with finding relevant electronic documents based upon a query. For example, given a group of keywords (the query), a search engine retrieves Web pages (documents) and displays them sorted by relevance to the query. This technology requires a way to compare a document with the query to see which is most relevant to the query.
A simple way to make this comparison is to compute the binary cosine coefficient. The coefficient is a value between 0 and 1, where 1 indicates that the query is very similar to the document and 0 indicates that the query has no keywords in common with the document. This approach treats each document as a set of words. For example, given the following sample document:
“Chocolate ice cream, chocolate milk, and chocolate bars are delicious.”
This document would be parsed into keywords where case is ignored and punctuation discarded and turned into the set containing the words {chocolate, ice, cream, milk, and, bars, are, delicious}. An identical process is performed on the query to turn it into a set of strings. Once we have a query Q
represented as a set of words and a document D
represented as a set of words, the similarity between Q
and D
is computed by:
Modify the StringSet
from Programming Project 12 by adding an additional member function that computes the similarity between the current StringSet
and an input parameter of type StringSet
. The sqrt
function is in the cmath
library.
Create two text files on your disk named Document1.txt
and Document2.txt
. Write some text content of your choice in each file, but make sure that each file contains different content. Next, write a program that allows the user to input from the keyboard a set of strings that represents a query. The program should then compare the query to both text files on the disk and output the similarity to each one using the binary cosine coefficient. Test your program with different queries to see if the similarity metric is working correctly.
Redo Programming Project 6 from Chapter 9 (or do it for the first time), but this time encapsulate the dynamic array and array size within a class. The class should have public member functions addEntry
and deleteEntry
. Make the array and size variables private. This will require adding functions for getting and setting specific items in the array as well as returning the current size of the array. Add a destructor that frees up the memory allocated to the dynamic array. Also, add a copy constructor and overload the assignment operator so that the dynamic array is properly copied from the object on the right-hand side of the assignment to the object on the left-hand side. Embed your class in a suitable test program.
To combat election fraud, your city is instituting a new voting procedure. The ballot has a letter associated with every selection a voter may make.
A sample ballot is shown.
VOTE FOR MAYOR
Pincher, Penny
□
Dover, Skip
□
Perman, Sue
□
PROPOSITION 17
YES
□
NO
□
MEASURE 1
YES
□
NO
□
MEASURE 2
YES
□
NO
□
After submitting the ballot, every voter receives a receipt that has a unique ID number and a record of the voting selections. For example, a voter who submits a ballot for Sue Perman, Yes on Proposition 17, No on Measure 1, and Yes on Measure 2 might receive a receipt with
ID 4925 : CDGH
The next day the city posts all votes on its Web page sorted by ID number. This allows a voter to confirm their submission and allows anyone to count the vote totals for themselves. A sample list for the sample ballot is shown.
ID | VOTES |
---|---|
4925 |
CDGH |
4926 |
AEGH |
4927 |
CDGI |
4928 |
BEGI |
4929 |
ADFH |
Write a program that reads the posted voting list from a file and outputs the percent of votes cast for each ballot item. You may assume that the file does not have any header lines. The first line will contain a voter ID and a string representing votes. Define a class named Voter
that stores an individual’s voting record. The class should have a constructor that takes as input a string of votes (for example, “CDGH”), a voter ID, and accessor function(s) that return the person’s ID and vote for a specific question. Store each Voter
instance in an array or vector. Your program should iterate over the array to compute and output the percent of votes cast for each candidate, proposition, and measure. It should then prompt the user to enter a voter ID, iterate over the list again to find the object with that ID, and print his or her votes.
Repeat Programming Project 11 from Chapter 10 but use an array to store the movie ratings instead of separate variables. All changes should be internal to the class so the main function to test the class should run identically with either the old Movie
class or the new Movie
class that uses an array member variable.
Next, modify the main function so that instead of creating separate variables for each Movie
object, an array of at least four Movie
objects is created with sample data. Loop through the array and output the name, MPAA rating, and average rating for each of the four movies.
Do Programming Project 16 from Chapter 8 except use a Racer
class to store information about each race participant. The class should store the racer’s name, bib number, finishing position, and all of his or her split times as recorded by the RFID sensors. You can choose appropriate structures to store this information. Include appropriate functions to access or change the racer’s information, along with a constructor. Make an array or vector of Racer
objects to store the entire race results.
The racer’s name should come from a separate text file. The information for this file is collected before the race when the participant registers for the event. Listed below is a sample file:
100,Bill Rodgers
132,Frank Shorter
182,Joan Benoit
Do Programming Project 19 from Chapter 8 except use a class named Player to store a player’s name and score. Use either a single array or vector of type Player. Be sure to include a constructor with this class that sets the name and score.