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.
- The name of the counter.
- The counters initial value.
- The counters final value.
- 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
Counter + 1
Sum = sum + counter
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