C++ Primer Plus Chapter 5 Exercise 3

c plus plusIf you love word problems, then you’ll love this one. And if you hate them, well then…Exercise 3 has some wordiness you must get through in order to understand what is going on. Overall, it’s not too bad. We use a while loop to keep track of some simple interest calculations, when one is bigger then the other, we break out of the loop and display our current values.  Here is my solution:

3. Daphne invests $100 at 10% simple interest. That is, every year, the investment earns
10% of the original investment, or $10 each and every year:
interest = 0.10 × original balance
At the same time, Cleo invests $100 at 5% compound interest. That is, interest is 5% of
the current balance, including previous additions of interest:
interest = 0.05 × current balance
Cleo earns 5% of $100 the first year, giving her $105. The next year she earns 5% of
$105, or $5.25, and so on. Write a program that finds how many years it takes for the
value of Cleo’s investment to exceed the value of Daphne’s investment and then displays
the value of both investments at that time.


#include <iostream>

using namespace std;

int main()
{
int years = 1;
double DaphneInvestment = 0;
double CleoInvestment = 0;

DaphneInvestment = 100 + (100 * 0.10);
CleoInvestment = 100 + (100 * 0.05);

while(CleoInvestment < DaphneInvestment)
{
DaphneInvestment+=10; // Daphne gets 10 dollars a year.
CleoInvestment = CleoInvestment + (CleoInvestment * 0.05); // Cleo gets her investment, plus 5%
years+=1; // increment the year.
}

cout << "Daphne's investment value is: " << DaphneInvestment << endl;
cout << "Cleo's investment value is: " << CleoInvestment << endl;
cout << "It took " << years << " years for Cleo's investment to exceed Daphne's investment" << endl;

return 0;
}