Loops

Loops are a piece of code that repeats its self multiple times. There are basically two main types of loops. For loops, and conditional loops.

A for loop is a piece of code that runs a predetermined number of times or a predetermined number of iterations. To create a for loop you need four pieces of information.

  1. The name of the counter.
  2. The counters initial value.
  3. The counters final value.
  4. The counter incrementation.
*English*
You want to find the sum of the first five numbers. 
1,2,3,4, and 5. 

*Code*
For Counter = 1, counter <= 5, counter = counter + 1
   sum = sum + counter
next Counter

For is the keyword that indicates you are creating a for loop.

Counter = 1
is the first two pieces of information. The counter variable in this case named counter and the initial value in this case 1.
Counter <=5
is the third piece of information. The loop will stop continue for as long as counter is less then 5.
Counter + 1
is the fourth piece of information. At the end of every iteration the value of counter will be incremented by one.
Sum = sum + counter
is the body of the loop. It is the portion of the loop that will be run multiple times.

and next counter indicates that it is the end of the body of the loop. It is telling the program to goto the next iteration of the for loop that uses the variable counter as its counter variable.


As you can tell in most normal uses of the for loop it will only run a predetermined number of times. The loop above will run five times, no more, no less. But what happens if you don't know exactly how many times you want a loop to run? No problems, this is where a conditional loop comes into play. There are two main conditional loops. Do…while loops, and while… do loops. The only difference between the two is that the do…while loop will always run at the very least one time, whereas the while…do loop may not run at all.

*English* 
Always find out if the player wants to play again. Ask him for a "y" for yes and a "n" for no answer.
If the player gives an answer that is not a "y" or an "n" ask him again. 

*Code*
do
    input "Would you like to play again? (Y=yes N=No) ",answer
    answer = LCASE(answer)    'Switch answer to all lowercase
loop while answer <> "y" and answer <> "n"
*English*
Add 100 points for every star a player has collected if the player has collected any stars.

*Code*
do while stars > 0
    score = score + 100
    stars = stars - 1
loop
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 2.5 License.