compound Interest
setup Form
btnShow
- for loops: specified number of iterations
- do-while loops: post-test condition, so will always run 1 or more times
- while-do loops: pre-test condition, so could run 0 or more times
- recursion: invoked method that invokes itself from within itself
int principal = 1000; //invest $1000
double rate = 0.10; //at 10% per annum
int time = 5; //for 2 years
double final_amount = 0; //total after investing
int counter = 0; //counter to control loops
//FOR LOOP--------------->
final_amount = principal;
for(counter = 1; counter <= time; counter++){
final_amount = final_amount + (final_amount * rate);
}
lblForLoop.setText(String.valueOf(final_amount));
//----------------------->
//DO WHILE--------------->
final_amount = principal;
counter = 1;
do{
final_amount = final_amount + (final_amount * rate);
counter++;
} while (counter <= time);
lblDoWhile.setText(String.valueOf(final_amount));
//----------------------->
//WHILE DO--------------->
final_amount = principal;
counter = 1;
while(counter <= time){
final_amount = final_amount + (final_amount * rate);
counter++;
}
lblWhileDo.setText(String.valueOf(final_amount));
//----------------------->
//RECURSION (HIGHER DIFFICULTY)--------------->
final_amount = compound(principal, rate, time);
lblRecursion.setText(String.valueOf(final_amount));
//-------------------------------------------->
create recursive method
- recursion is like inception. google it. put this were you would normally declare sub-methods for your class (outside your button event handler).
public double compound(double p, double r, int t){
if (t == 0)
{
return p;
}
else
{
return (compound(p + (p * r), r, t-1));
}
}