Loops are statements as well. They work very similar to the if-statement with the only exception that they will continue to repeat their code for as long as their condition is met. The conditions are constructed just as in an if-string.
While is the simplest loop of them all, using only that statement and containing nothing else but one single expression, which conditions are also being called. Let me show you an example of how a simple expression/condition and how the while-string could be used:
a = 0;
while (a<10) {
a+=1;
}
show_message(string(a));
What we are basically doing is that we first assign the variable a and set it to zero. Then while a (which is currently zero) is below ten the expression returns true and thus the code will be �looped� all over again. After the first run a is equal to one, then after the second two, then three, then four and so on until a equals ten. When a equals ten the function show_message is executed for the first time. Show_message is a very simple function that displays a value. As you read in the beginning of this chapter there are two different kind of values, string value and real values. Only string values may be drawn in a pop-up window such as the one that show_message generates therefore we are converting it with the string(x) function.
For might be the most complicated loop-statement of the three because it does all that do and while does but in one single line. It first initializes a value, and then compares it with the expression and then it manipulates it... like this:
for (i=0; i<=9; i+=1) list[i] = i+1;
Again; i=0 initializes (assigns) the variable i to zero. Then it checks if i is smaller or equal to nine, and if it is, it adds one to I; then the code outside the parenthesis is executed and it starts all over, but skips i=0, so it checks if 9 is still smaller or equal to 9. In the end i will equal ten, just as if you would have written i<10 instead of i<=9� If you got more code than in the example above you may use brackets, which I have been using earlier, and which looks like this { } :
for (i=0; i<=9; i+=1) {
//Code to be executed here
}
Do is another version of a loop where you put the expression at the end instead of in front. To indicate that it should loop anyway you must put do in front, the expression comes later with until, which looks like this:
b = 9;
do
{
a+=1
}
until (a>b)
So it will execute the code a+=1 until a is larger than b. In the end a will be ten. As you will surely have realized this is the reversed version of while, which is executed while the expression returns true and until executes until the expression returns true.
.
Users logged in:
Comments
Loading comments...