reccursive program

I am trying to make a recursive program that calculates interest per year.It prompts the user for the startup amount (1000), the interest rate (10%)and number of years(1).(in brackets are samples)

Manually I realised that the interest comes from the formula YT(1 + R)----- interest for the first year which is 1100.

2nd year YT(1 + R/2 + R2/2) //R squared

2nd year YT(1 + R/3 + R2/3 + 3R3/) // R cubed

How do I write a recursive program that will calculate the interest? Below is the function which I tried

Problem : Results are not correct. Expected results if startUp amount is 1000, interest 10% for 1 year would be 1100. Two years would be 1210

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double calculateInterest(double startUp, double rate, int duration)
{
 double cpdInterest = (duration*startUp)*(1 + rate);
 
 if (duration == 0) 
     {
      return cpdInterest;
     }
     else if (duration < 0) 
        {
          cout << "Please enter a valid year";
        }
     else
     {
     calculateInterest(cpdInterest, rate, duration - 1); 
     }
     return (startUp*rate) + calculateInterest(startUp*(1+rate), rate, duration-1); 

}


Last edited on
1. The algorithm as you've presented it isn't recursive.
2. You shouldn't be prompting for input in the middle of a computation, you should ask for parameters and pass them into the function.
Topic archived. No new replies allowed.