Recommended Practice
Recommended Practice
Notes:
• This is not a practice midterm, meaning questions may di=er in format and length from the actual
midterm. These questions are to help you evaluate your understand of the topics
• Feel free to prerace more questions from the textbook (there are some great ones!)
• Remember to review the lecture notes, lab content and assignment content as well in preparation
for the midterm
• R-2.7 • C-3.6
• R-2.13 • C-3.13
• R-2.14 • P-3.3
• P-2.5 (only do Polygon, Triangle and • R-4.5
EquilateralTriangle) • R-4.13
• R-3.6 • C-5.5
• R-3.17 • P-5.5
Solutions:
• R-2.7
o A class may have many di=erent constructors. The compiler cannot know which of the
base class’s constructors would be appropriate to be called, or what arguments should
be passed to it. So the derived class must make the call explicitly. There is only one
destructor for any class, and so there is no choice involved. Further, since destructors
are not explicitly called by the user (they are invoked automatically by the system),
there is no way for a derived class to even invoke it base class’s destructor.
• R-2.13
o Let us assume that we define an exception class ArrayIndexBounds, whose constructor
is given the index value that caused the error. It has a member function badIndex that
returns this index. The following code checks for the array subscript out of bounds, and
if so, outputs an appropriate error message. (It is more likely that there is a class storing
the array, and this class would throw the exception.)
try {
if (i >= array.size())
throw ArrayIndexBounds(i); cout << array[i];
}
catch(ArrayIndexBounds& e) {
cout << "Array index ";
cout << e.badIndex() << " is out of bounds.";
}
Copyright Jocelyn Minns – Do Not Repost
• R-2.14
o Read it.
Ship it.
Buy it.
Read it.
Box it.
Read it.
• P-2.5
o See file: inheritance.cpp on Brightspace
• R-3.6
o Create a data member nElem storing the number of elements. Increment it with each
addition and decrement it with each removal.
• R-3.17
o int countNodes(Node* head) {
if (head == nullptr) return 0;
int count = 1;
Node* current = head->next;
while (current != head) {
++count;
current = current->next;
}
return count;
}
• C-3.6
𝑛 if 𝑚 = 1
o product(𝑚, 𝑛) = .
𝑛 + product(𝑚 − 1, 𝑛) oterwise
• C-3.13
int stringToInt(const std::string& str, int index = 0) {
if (index == str.length() - 1)
return str[index] - '0';
o
• C-5.5
o To implement the stack ADT using two queues, Q1 and Q2, we can simply enqueue
elements into Q1 whenever a push call is made. This takes O(1) time to complete. For
pop calls, we can dequeue all elements of Q1 and enqueue them into Q2 except for the
last element which we set aside in a temp variable. We then return the elements to Q1
by dequeuing from Q2 and enqueuing into Q1. The last element that we set aside earlier
is then returned as the result of the pop. Thus, performing a pop takes O(n) time
• P-5.5
o See file: queue.cpp on Brightspace