The while loop executes statements as long as some condition is true. It is used as the following code illustrates:
def main()
{
data = 1;
while (data) {
data = input();
println("got your input.");
}
}
This executes the blocked lines until the input is 0. With while, the condition is evaluated first, so if it is initially false, the loop will never execute. That is why we had to put "data = 1;" before the while -- putting "data = 0;" would cause the loop to never execute. In this scenerio, it would be more appropriate to use the while in the following form:
def main()
{
do {
data = input();
println("got your input.");
} while (data)
}
As you can see, if you preceed the block (or statement) with the word "do," you can up the while after the block, and this postpones the condition check until after the block executes.
Another kind of looping comes from the for construct. You use this to make incremental loops, or loops where in each pass a variable is changed in some way. The simplest example follows:
def main()
{
for(k in 1..10)
println(k);
}
This will print the integers from 1 to 10 on the screen. You give for a variable first, in this example it is k. Then put the word "in" and then a range for the variable to be in. The loop executes, first with the variable equal to the beginning of the range, then incrementing the value by 1 every time the loop finishes until it has reached the end of the range. You can make the range from high to low to count backward, so changing the "for" line in the above example to for(k in 10..1) would print the numbers from 10 down to 1. The for construct also has uses in lists, which are covered in that part of the Tutorial.
The simplest use of the for loop doesn't use variables at all. If you supply an integer in the for parentheses, the block is executed that many times.
The next section in the Tutorial covers lists.
Web page maintained by Jason Cohen