Interest While Loops

I can't really pinpoint what's wrong here. This question asks how many years it would take for the investment to double with a given contribution, but with no contribution in year zero. The years output comes up good, but the balance is always off. Thanks in advance for any help, I have trouble with one off errors in loops for some reason.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>
#include <iomanip>
using namespace std;

int main()
{  
   const double RATE = 5;
   const double INITIAL_BALANCE = 10000;
   const double TARGET = 2 * INITIAL_BALANCE;
   
   cout << "Annual contribution: " << endl;
   double contribution; 
   cin >> contribution;

   double balance = INITIAL_BALANCE;
   int year = 0;

   // TODO: Add annual contribution, but not in year 0
   while(balance < TARGET)
   {
      
      balance = balance + contribution;
      double interest = balance * RATE / 100;
      balance = balance + interest;
      year++;
   }
   
   cout << "Year: " << year << endl;
   cout << "Balance: " << balance << endl;

   return 0;
}
Look at your loop. Exactly where in the code did you say "add the annual contribution except in year zero"?
So are you saying add a conditional like this?

1
2
3
4
5
6
7
8
9
10
if(year == 0){
     double interest = balance * RATE / 100;
     balance = balance + interest;
     year++;
} else {
     balance = balance + contribution;
     double interest = balance * RATE / 100;
     balance = balance + interest;
     year++;
}


EDIT: Nevermind, I added this conditional and it worked just fine. Thanks!
Last edited on
It works, but there's a lot of duplicated code there. That needlessly clutters the code, and makes it more error-prone. Your code would be better if you re-organized it to avoid that.
Topic archived. No new replies allowed.