CS 215 - Fundamentals of Programming II 20 points

advertisement
CS 215 - Fundamentals of Programming II
Spring 2011 - Homework 9
20 points
Out: February 23
Due: February 28 (Monday) at the beginning of class; no late work accepted
This homework consists of some sample problems similar to what will be on the written midterm
exam. (Note: this is not an exhaustive sample of all possible question types. All previous homework
problems should be considered samples as well.) We will go over these problems during the exam
review on Monday.
1. (3 points) A complex number has the form√a+bi, where a (the real part) and b (the imaginary
part) are real numbers, and i represents the −1. The following (partial) class Complex models
a complex number.
class Complex
{
public:
Complex (double a = 0, double b = 0);
// Explicit value constructor: a+bi; default value is 0+0i
double RealPart() const;
// return real part
double ImaginaryPart() const;
// return imaginary part
private:
double real, imag;
// (real)+(imag)i
};
Write the prototype and function definition for a member function Magnitude that returns the
magnitude of a complex number. The magnitude of a complex number of the form a+bi is
√
a2 + b2 . The C++ functions for square root and exponentiation are sqrt and pow, respectively.
2. (3 points) Write a recursive function Reverse that has three parameters: an array of integers
arr and indexes first and last. This function is to reverse the contents of the array in range
[first, last), i.e., from arr[first] to arr[last-1]. For example, if the array arr contains values
1 2 3 4 5, then after the function call Reverse(arr, 1, 4), arr’s values will be 1 4 3 2 5.
3. (4 points) Write a function CountItem that receives two parameters, an STL vector of strings v
and an string search value t, and returns the number of elements in v that are equal to t. Assume
strVector is a vector of strings. Write a code fragment using CountItem that will display the
number of times "C++" appears in strVector.
1
4. (10 points) Consider the following (partial) class that implements a dynamic array of integers.
A dynamic array behaves just like a static array except that its size is set at run-time during
construction. After it is constructed, it cannot change size.
class DynamicArray
{
public:
DynamicArray (int initSize = 1, int initValue = 0);
// Explicit value constructor:
//
creates array of initSize integers to store data
//
elements initialized to initValue
int & operator[] (int index); // indexing operator returns arr[i]
private:
int *arr;
size_t capacity;
// pointer to data storage
// number of elements in the array
};
Answer the following questions
a. Write the function definition for the explicit-value constructor that behaves as indicated in
the comments above.
b. Write the prototypes and function definitions for the destructor, copy constructor, and assignment operator (operator=) for this class.
2
Download