The While loop is the most basic loop. To start a while loop, rather than using
if to begin your statement, as with conditional statements, you write
while. Here's an example:
This script will repeat itself infinitely as long as x is less than 100. You need to tell it to stop looping.
You can stop the loop in a couple of ways. One way is to increment the variable so that at some point, the condition is no longer met:
Now the script will repeat 99 times. With each iteration, x increments by 1. Once x gets to 100, the code won't execute because the condition
( x > 100 ) isn't met.
Do ... While Loops
There's another way to stop a loop. Rather than beginning with
while, you can use the "Do ... While" format:
The Do ... While loop differs in that you put the condition after the code block. This means the code block will run at least once regardless of the condition. Once the code block runs and the condition is asked, the loop continues only if the condition is met.
Loops typically have three components: an index, a condition, and an increment to the index. The index is a variable you use to start counting your loop. Written out the long way, the statement would look as follows:
Because loops are so common, you can write this statement in a more abbreviated way using the
for loop. With the
for loop, you start the statement with the word
for. You then insert the conditions and increment value in parentheses separated by semicolons. You then add the code block. Here's an example:
Break and Continue
You can stop a loop using the words
Break exits the loop, whereas
continue stops the current command and rechecks the conditions to see if the loop can start again at the top.
Here's an example with