# Giving money to the bank

Lets say we need to write an algorithm for giving money to the bank. We need to know interest rate, money which we put every year on our account, and amount of money we want to get. F.e int. rate is 1%, money we put every year is 1000 (or whatever) and we want to get 10000 (not more). It'd look like this:

1. MoneyOnAcc=1000*1.01
2. MoneyOnAcc=(MoneyOnAcc+1000)*1.01
3. Until MoneyOnAcc reaches 10000 (we want to print amount what was before 10000 - 9462.21)

and so on. Here is my code in Pascal.

program whilel;

var interestRate:real;
moneyEveryYear:real;
accMoneyOut:real;
totalAmount:real;
accMoneyControl:real;
begin

while accMoneyOut<totalAmount do begin
accMoneyControl:=(accMoneyOut+moneyEveryYear)*((interestRate/100)+1);

if accMoneyControl>totalAmount then break;

accMoneyOut:=(accMoneyOut+moneyEveryYear)*((interestRate/100)+1);

end;
writeln(accMoneyOut:6:2);
end.


How can I improve this algorithm? Maybe some better logic will help.

• Where did you find the docs for your use of WriteLn(GAccMoneyOut:6:2)? Commented Nov 12, 2015 at 22:52
• It was in a book :-)) Commented Nov 14, 2015 at 10:54
• Would love to know which book :) Commented Nov 14, 2015 at 19:53
• I'm from Slovakia so it's a Slovak book. Why are you asking ?? Is there something wrong? :) Commented Nov 14, 2015 at 22:26
• I am genuinely curious about it! I didn't know it was possible in this straightforward way. Commented Nov 16, 2015 at 21:03

• Care about indentation. Pascal is usually written with 2 space indentation.

• Repeat is a posttest loop, and your code needs to run at least once, so why not a repeat..until loop. You can save a begin..end block, as well.

• you should explain to your self the inputs, unite measures and all the info you need to properly insert the requested variables.

• in pascal, prefixing your own variables is good practice for complex code (not your case). Take a look at this answer. I choose to prefix our global variables with 'G'; Also, functions and procedures goes with CapitalLetters.

• Avoid repetition, I choose to use GAccMoneyOut:=GMoneyControl; instead of repeating the code to raise the money.

Putting all together:

program whilel;

uses Crt;

var
GInterestRate,
GMoneyEveryYear,
GTotalAmount,
GMoneyControl,
GAccMoneyOut:real;

begin
WriteLn('Enter the porcentage interest rate');

WriteLn('Enter the money you will put every year into the account');

WriteLn('Enter the money you want to get');

GAccMoneyOut:=0;
GMoneyControl:=0;
repeat
GMoneyControl:=(GAccMoneyOut+GMoneyEveryYear)*((GInterestRate/100)+1);
if GMoneyControl>GTotalAmount then
Break
else
GAccMoneyOut:=GMoneyControl;
until GAccMoneyOut=GTotalAmount;

WriteLn('Result is:');
WriteLn(GAccMoneyOut:6:2);

WriteLn('Press any key to exit...');