Seamus

Some people take to the concepts of loops naturally... for others it 
is a mental block.

Not to worry!

The classic programming problem which illustrates the need for loops 
is the "Native American" Problem:

   The Dutch purchased Manhattan Island from the "Native Americans" 
for $18.00 in
   er, ah... lets say 1624.  If the money were invested at 4%, compounded
   annually, what would it be worth today.

To solve you could write out:

   Year: 1624  Value: $18.00
   Year: 1625  Value: $18.00 * 1.04
   Year: 1626  Value: $18.00 * 1.04 * 1.04
    .
    .
    .

so we would do the 375 steps to get to 2001

Now if we look closely, we notice a certain consistency in the 
operations performed in each step:

   the year is incremented by 1

   the amount is incremented by 4& ( Amount * 1.04 )

Regardless of which step (year) the calculations are always the 
same... the 2 operations are repeated over and over.

To write this out abstractly we could say:

   Start with an amount of $18,00

   Start at a year of 1624

     Repeat

       Add 1 to the year

       Multiply the amount by 1.04

     until the year is equal to 2001

What controls the number of times we repeat, is the year (incremented)


Now, we take this and rewrite this in CF"

    <cfset amount=18.00>

    <cfloop index=theYear from=1624 to=2001 step=1>

      <cfset amount = amount * 1.04>

    <cfloop>

Now if you compare the two, you see that the <cfloop> tag combines 
the operations of:

     setting the starting and ending values for year

     setting the increment for year

     testing for the end value of year.

So all we have to do is compute the amount and indicate the end of the loop.

Now, if you change the problem slightly:

   The Dutch purchased Manhattan Island from the "Native Americans" 
for $18.00 in
   er, ah... lets say 1624.  If the money were invested at 4%, compounded
   annually, when would the value exceed $200,000?

.... we'll cover that in the next installment,

HTH

Dick


At 11:17 AM +1000 7/13/01, Seamus Campbell wrote:
>Many thanks  again.
>
>Slightly OT - I have learnt CF without any background in programming - I
>have a huge problem getting loops and lists  to work - I can understand the
>general principles but just can't seem to be able to learn to implement
>specific code.
>
>For instance I can see what you are doing in the code below and I can adapt
>code that other people have done (often by trial and error rather than logic)
>BUT i have huge problems coding loops and lists on my own.
>
>Is this normal - or am I just slow???
>
>Any ways to learn how to "roll my own"  ???
>
>Many thanks
>Seamus
>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Structure your ColdFusion code with Fusebox. Get the official book at 
http://www.fusionauthority.com/bkinfo.cfm

Archives: http://www.mail-archive.com/cf-talk@houseoffusion.com/
Unsubscribe: http://www.houseoffusion.com/index.cfm?sidebar=lists

Reply via email to