Solution to probelem 5 in C++