This week's book giveaway is in the Other Languages forum.We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Calculating a total after a "for" loop

Deena Lee
Greenhorn
Posts: 13
Friends,
I have a for loop that adds on a monthly interest rate to two different account balances and prints the new balance for each month 0 - 12. (this part works great!) After it goes through the process I am suppose to print the balance of the accounts added together. The problems is when I do this, I get an extra months worth of interest for both accounts in the total.

Here is my "For loop" code with the subsequent print statement:

Any help would be appreciated!
Thanks,

fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
you realize you are looping 13 times, right?

Deena Lee
Greenhorn
Posts: 13
fred rosenberger wrote:you realize you are looping 13 times, right?

Yes, I did realize I was looping 13 times. I needed an initial total; plus, 12 months of interest. Thanks for the reply though.

However, Idid manage to get it fixed. I simply put the initial month 0 in a separate print statement prior to the loop so I only needed 12 iterations of the loop.

fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
I would say that is the right solution.

You needed to do this:

print the values 13 times

So having a loop with a counter of 13 with both printing and adding interest is going to get you an extra month of interest. Your loop should only have a counter of 12. Then, depending on exactly how you write it, you could either

or

Either one would get you 12 months of interest, and print the values 13 times. It's actually pretty common to do things this way.

Soniya Ahuja
Ranch Hand
Posts: 83
Another way of fixing the existing code would have been to add the monthly interest only for months 1 to 12.

So you would have the calls enclosed in an if statement

Now the existing code would work, but anyway you have found a fix already

Campbell Ritchie
Sheriff
Posts: 50232
79
I prefer the earlier solution with a statement outside the loop.

Soniya Ahuja
Ranch Hand
Posts: 83
@Campbell - I was just trying to modify the existing code here
But yes I agree, a statement outside the for loop, before the loop actually starts is more readable and even the for loop will then work for the purpose it is required to fulfill - calculating interest for 12 months.

Campbell Ritchie
Sheriff
Posts: 50232
79
So we agree in the end

Soniya Ahuja
Ranch Hand
Posts: 83
When did I disagree with you