Reputation: 1
I wrote a loop :
for(int i = 0; i<=5;i++){
Double endingBalance = savingsAmount1 * (1+ (monthlyInterestRate1*i));
for the following calculation, however the loop does not output the correct values. savingsAmount1 and monthlyInterestRate1 are both user inout values. Any thoughts on how to get this working correctly? Should I prompt an input for months and loop months as well?
Double endingBalance = savingsAmount1 * (1+ (monthlyInterestRate1*i));
double firstMonthEndingBalance1 = savingsAmount1 * (1 + monthlyInterestRate1);
double secondMonthEndingBalance1 = (savingsAmount1 + firstMonthEndingBalance1) * (1 + monthlyInterestRate1);
double thirdMonthEndingBalance1 = (savingsAmount1 + secondMonthEndingBalance1) * (1 + monthlyInterestRate1);
double fourthMonthEndingBalance1 = (savingsAmount1 + thirdMonthEndingBalance1) * (1 + monthlyInterestRate1);
double fifthMonthEndingBalance1 = (savingsAmount1 + fourthMonthEndingBalance1) * (1 + monthlyInterestRate1);
double sixthMonthEndingBalance1 = (savingsAmount1 + fifthMonthEndingBalance1) * (1 + monthlyInterestRate1)
Upvotes: 0
Views: 45
Reputation:
Try putting your variable on the outside of the loop:
Double endingBalance = savingsAmount1;
for(int i = 0; i<=5;i++) {
endingBalance = endingBalance * (1 + monthlyInterestRate1);
}
The way it is working now, your endingBalance
is being recreated for each step of your loop (effectively resetting it to savingAmount * 1+monthlyInterest
each time). With compound interest you want to multiply your interest against the total balance each step (which requires you track it outside of the loop).
Further Explanation:
What you were using before was a local variable that only has scope within the for
block. By moving it outside of that for
block, you grant it greater scope so it can exist even after the for
block terminates.
Upvotes: 1