Trivial program to calculate compound interest, I = P(1+n)^y.
public class Interest {
public static void main(String[] args){
double sum = calculate(1000,10,3);
System.out.println(sum);
//sanity check, using non-recursive formula:
double amt = 1000*(Math.pow(1 + 0.1, 3));
System.out.println(amt);
}
public static double calculate(double initialAmount, double interest, int years){
double yearly = initialAmount + initialAmount*(interest/100);
System.out.println("calculate is called with P = " + initialAmount + ", interest = "+interest+", and years = " + years);
System.out.println("This year's amount: "+yearly);
if (years <= 0){
return initialAmount;
}
if (years == 1){
return yearly;
}
else {
return yearly + calculate(yearly, interest, years - 1);
}
}
}
The output is as follows (notice that YEARLY is calculated correctly but not returned as expected):
debug:
calculate is called with P = 1000.0, interest = 10.0, and years = 3
This year's amount: 1100.0
calculate is called with P = 1100.0, interest = 10.0, and years = 2
This year's amount: 1210.0
calculate is called with P = 1210.0, interest = 10.0, and years = 1
This year's amount: 1331.0
3641.0
1331.0000000000005
When I debug, execution enters if (years == 1) as expected, but then also enters the following else block. How can it enter both branches? Please advise; I've been racking my brains, and restarting the computer and NetBeans didn't help.
elseis in one recursive depth ABOVE. please check theyearsvariable. It should be2if you are in theelseblock.