What are Loops and how do they work

written by: Milan Midovich; article published: year 2007, month 07;

In: Root » Computers and technology » Flash

  Share  
|
  PL  |  NL  |  FR  |  ES  |  PT  |  IT  |  DE  |  DK  |  NO  |  SE  |  FI  |  GR  |  JP  |  CN  |  KR  |  RU  |  AE


Computers are great for doing repetitive tasks. Whereas a human gets bored doing the same thing a few times in a row, a computer is happy to repeat the same task hundreds or even millions of times. In fact, repetitive tasks are where computers really excel.

Looping is an important part of every programming language. ActionScript is no exception. You can repeat a set of instructions a certain number of times, or until a certain condition is met.

In fact, conditions are an important part of looping. All a loop needs is a starting and ending point, plus a condition that signifies the end of the loop.

For instance, if you want to loop 10 times, a variable will be used to start counting at 0. Each time the loop loops, the counter is incremented by 1. When it reaches 9, the loop ends and the program continues past the end of the loop. The following is an illustration of a typical program loop:

  1. Some command before loop.

  2. Start of loop, counter set to 0.

  3. Some command in loop.

  4. Some other command in loop.

  5. Counter incremented by 1.

  6. If counter is less than 9, go back to step 3.

  7. Some command after loop.

In the preceding seven steps, step 1 only happens once. Then step 2 signifies the beginning of the loop. Steps 3, 4, 5, and 6 are executed 10 times. After the 10th time, step 7 is executed, and the program continues from there.

So if the loop is to occur 10 times, why does it check to see whether the counter reaches 9? This is because the counter starts at 0. This is typical of most computer programming languages. The counter counts from 0 to 9 instead of from 1 to 10.

Another important part of loops is when, exactly, the condition is examined. In some cases, it is examined before the commands in the loop are executed, and in other cases it is examined in the end.

There are also ways to break out of loops prematurely, and ways to skip the rest of the commands in a loop and start back at the beginning.

Share

Disclaimer

1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us or use the "Report this article" button on this page to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here.