C++ code for exercise 7