Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Exercises 14.14 Coding Practice

1.

Below is the struct definition for Room, which has a length, width, and height. It also has two member functions, calculateArea and calculateVolume. Turn this struct into a class with private member variables.
Solution.
Below is the class definition of Room. As you can see, there isn’t a big difference between structs and classes.
#include <iostream>
using namespace std;

class Room {
private:
    int length;
    int width;
    int height;

public:
    int calculateArea () {
        return length * width;
    }

    int calculateVolume () {
        return length * width * height;
    }
};

2.

There are errors in the code below. Modify the code so that main runs successfully. Check the hint below for help with the construction of the code.
Hint.

Activity 14.14.1.

There are errors in the code below. Modify the code so that main runs successfully. Use the lines to construct the code, then go back to complete the Activecode.

3.

Below is the class definition for Temp. Write the private member functions cToF and fToC, which converts Celsius to Fahrenheit and vice versa and returns the conversion. Update getFahrenheit and so that if is_celsius is true and a user calls getFahrenheit, it will call cToF and return the correct temperature in degrees Fahrenheit. Do the same for getCelsius.
Solution.
Below is one way to implement this. We use the correct conversions in cToF and fToC and then call these functions in getFahrenheit and getCelsius if needed.
#include <iostream>
using namespace std;

class Temp {
private:
    double fahrenheit;
    double celsius;
    bool is_fahrenheit;
    bool is_celsius;

    double cToF() {
        return celsius * 9/5 + 32;
    }

    double fToC() {
        return (fahrenheit - 32) * 5/9;
    }

public:
    double getFahrenheit () {
        if (is_celsius) { return cToF(); }
        else { return fahrenheit; }
    }
    double getCelsius () {
        if (is_fahrenheit) { return fToC(); }
        else { return celsius; }
    }
    void setFahrenheit (double f) { fahrenheit = f; is_fahrenheit = true; is_celsius = false; }
    void setCelsius (double c) { celsius = c; is_celsius = true; is_fahrenheit = false; }
    void printTemp () {
        if (is_fahrenheit) {
            cout << "It is " << getFahrenheit() << " degrees Fahrenheit" << endl;
        }
        else {
            cout << "It is " << getCelsius() << " degrees Celsius" << endl;
        }
    }
};

4.

In main create a Temp object to calculate what 100 degrees Celsius is in Fahrenheit. Check the hint below for help with the construction of the code.
Hint.

Activity 14.14.2.

In main create a Temp object to calculate what 100 degrees Celsius is in Fahrenheit. Use the lines to construct the code, then go back to complete the Activecode.

5.

We took a look at vectors in chapter 10, where we saw how we could add data to the end of a vector and remove data from the end of a vector. But what if we wanted to add and remove things at the beginning of a vector? Or we wanted to print out a vector without painfully constructing a loop every time? We can create our own MyVector class! Write the MyVector class, which has a vector of ints as a private member variable. Also write the default constructor.
Solution.
Below is the class definition of MyVector. We use the public and private keywords to separate public and private members of our class. The default constructor sets size to 0.
#include <iostream>
#include <vector>
using namespace std;

class MyVector {
private:
    vector<int> elements;

public:
    MyVector() {};
};

6.

What if we had an existing vector with data that we want to copy into our MyVector? Write a constructor that takes a vector and copies the data into the elements vector. Check the hint below for help with the construction of the code.
Hint.

Activity 14.14.3.

What if we had an existing vector with data that we want to copy into our MyVector? Write a constructor that takes a vector and copies the data into the elements vector. Use the lines to construct the code, then go back to complete the Activecode.

7.

The reason why we have elements as a private member variable is that people using our MyVector class don’t need to know how we implemented our class, so we can implement it however we want. This means for functions MyVector has that overlap with functions that vector has, we can just call the same function on our elements vector. Write the MyVector functions size , push_back, pop_back, and at. size returns the size of our MyVector. push_back takes an int and adds it to the end of our MyVector. pop_back removes the last element. at takes an index and returns the data stored at that index. Use existing vector functions to implement these MyVector functions!
Solution.
Below is one way to implement these functions. Since these functions are defined for vectors, we can call them on elements.
#include <iostream>
#include <vector>
using namespace std;

class MyVector {
private:
    vector<int> elements;

public:
    MyVector() {};
    MyVector(vector<int> vec);

    size_t size() { return elements.size(); }
    void push_back(int value) { elements.push_back(value); }
    void pop_back() { elements.pop_back(); };
    int at(int index) { return elements[index]; }
};

int main() {
    vector<int> data = { 2, 4, 1, 5, 2, 6 };
    MyVector myVec(data);
    cout << "The first element is " << myVec.at(0) << endl;
    myVec.pop_back();
    myVec.pop_back();
    myVec.push_back(12);
    cout << "The size of myVec is " << myVec.size() << endl;
    cout << "The last three elements are " << myVec.at(2) << ", "
         << myVec.at(3) << ", and " << myVec.at(4) << endl;
}

8.

Now we can write some of our own fun functions! No longer do we need to write for loops every time we want to print out a vector. With MyVector, we can just call the member function print! Write the MyVector member function print, which prints out the contents of MyVector. For example, if our MyVector contained the elements 2, 5, 1, and 8, print should print out [2, 5, 1, 8] followed by a newline. Check the hint below for help with the construction of the code.
Hint.

Activity 14.14.4.

Now we can write some of our own fun functions! No longer do we need to write for loops every time we want to print out a vector. With MyVector, we can just call the member function print! Write the MyVector member function print, which prints out the contents of MyVector. For example, if our MyVector contained the elements 2, 5, 1, and 8, print should print out [2, 5, 1, 8] followed by a newline. Use the lines to construct the code, then go back to complete the Activecode.

9.

Let’s write the MyVector member function push_front and pop_front. push_front should take a value and add it to the front of our MyVector, and pop_front should remove the first element.
Solution.
Below is one way to implement these functions. For push_front, we can create a temporary vector and add the new element to the front before pushing the rest of the old elements to the back. For pop_front, we can shift all elements up by one index and pop the last element off.
#include <iostream>
#include <vector>
using namespace std;

class MyVector {
private:
    vector<int> elements;

public:
    MyVector() {};
    MyVector(vector<int> vec);

    size_t size();
    void push_back(int value);
    void pop_back();
    int at(int index);
    void print();
};

void MyVector::push_front(int value) {
    vector<int> temp;
    temp.push_back(value);
    for (size_t i = 0; i < elements.size(); ++i) {
        temp.push_back(elements[i]);
    }
    elements = temp;
}

void MyVector::pop_front() {
    for (size_t i = 1; i < elements.size(); ++i) {
        elements[i - 1] = elements[i];
    }
    elements.pop_back();
}

int main() {
    vector<int> data = { 2, 14, 5 };
    MyVector myVec(data);
    myVec.pop_front();
    myVec.push_front(5);
    myVec.push_front(10);
    cout << "The new size is " << myVec.size() << endl;
    myVec.print();
}

10.

What if we wanted to return the largest and smallest elements in our MyVector? Write the public member functions max and min which calls the private member functions findMax and findMin. findMax and findMin return the indices of the max and min values, and max and min call these private member functions and return the max and min values. Check the hint below for help with the construction of the code.
Hint.

Activity 14.14.5.

What if we wanted to return the largest and smallest elements in our MyVector? Write the public member functions max and min which calls the private member functions findMax and findMin. findMax and findMin return the indices of the max and min values, and max and min call these private member functions and return the max and min values. Use the lines to construct the code, then go back to complete the Activecode. Be sure to declare the max and min functions in public when you complete the Activecode.
You have attempted 1 of 16 activities on this page.