Looping in Flash

A loop is a series of commands that are executed until a given condition is met. In Flash, there are two kinds of loops:

1.  for loops

2.  do...while loops

We are going to talk about the latter—the do...while loops.

Let's just say in plain English what we need those loops for. In short, we need them to instantly execute a given command (or commands)
a number of times. 

Now this is the basic code:

do {
statement(s)
} while ( condition )

I thought it might be a good way of exploring the intricacies of loops in Flash by using an interesting example.

Imagine that someone revealed the secret of eternal life, and 2006 years ago deposited one American dolar in a bank. The amount has been increasing by 1% every year.

What, do you think, the amount would be now?

The answer is: $466, 311, 159! That's over 466 million American dollars.

How can we calculate it?

We could calculate the amout using the formula for compound interest. Here it is:

A = P\left(1 + \frac{r}{n}\right)^{nt}

In "Flashian" (or "Flashish" if you will), that would be:

race(Math.pow(1.01, 2006))

However, to calculate the amount we are going to use a more primitive method—using a loop :-)

How to do it with a loop?

i. Create a new Flash document. The dimensions as well as the frame rate don't matter this time.

ii. Copy (ctrl + C) and Paste (ctrl + V) the following code on the first frame of the main Timeline—simply select the first frame and press F9.

money = 1;
year = 0;
do {
year++;
money = money + money *.01;
} while (year<2006);
trace(Math.round(money));

If you now press Ctrl + Enter, the output window should display
466, 311, 159.

Explanation

I'm sure some of you could do with an explanation. So, let's go!

money = 1;
year =0

I declare two variables: "money" and "year".

"money" is how much we start with—that's one dollar, so the variable is equal to 1.

"year" is the current year. It is equal to 0, because this is the year that we start from.

do {
money = money+ money*.01;

year ++;


This is the beginning of our loop. We can specify what commands we would like to be executed. There are two of them:

1. We increase the value of "money" by 1%
2. We increment (increase by 1) the variable "year". Another way of doing the same operation is by writing "year=year+1" or "year+=1".

} while (year<2006);


The looping will be going on as long as the variable "year" is smaller than 2006. This means that the actions between the opening and closing curly brackets ( { } ) will be executed 2006 times.

trace("$"+Math.round(money))


And finally,  we tell Flash to trace (=display) the value of "money".

As you can see, we rounded the number using the Math.round() function.  Oh, and just a detail: We added a $ mark at the beginning of the number.


So, I think this is it. We've done a pretty good job. Hope you've enjoyed this tutorial and found it helpful.

Cheers and good bye!

Average: 3.5 (8 votes)