-
Notifications
You must be signed in to change notification settings - Fork 3
Loops
These structures are called loops since the body is repeated (possibly) multiple times, reminiscent of a rope containing loops. Each pass through the loop is called an iteration. For more information, see https://en.wikipedia.org/wiki/Control_flow#Loops.
The rate is the time (in milliseconds) for one loop to occur. The rate block is necessary for any loop block.
The simplest "repeat" block runs the code in its body the specified number of times. For example, the following block will print "Hello!" ten times.
Imagine a game in which a player rolls a die and adds up all of the values rolled as long as the total is less than 30. The following blocks implement that game:
A variable named total gets an initial value of 0. The loop begins with a check that total is less than 30. If so, the blocks in the body are run. A random number in the range 1 to 6 is generated (simulating a die roll) and stored in a variable named roll. The number rolled is printed. The variable total gets increased by the roll. The end of the loop having been reached, control goes back to step 2.
When the loop completes, any subsequent blocks (not shown) would be run. In our example, the loop would end after some number of random numbers in the range 1 to 6 had been printed, and the variable total would hold the sum of these numbers, which would be guaranteed to be at least 30.
For more information, see https://en.wikipedia.org/wiki/While_loop.
The count with block (called a for loop in most programming languages) advances a variable from the first value to the second value by the increment amount (third value), running the body once for each value. For example, the following program prints the numbers 1, 3, and 5.
As shown by the two following loops, each of which prints the numbers 5, 3, and 1, the first input may be larger than the second. The behavior is the same whether the increment amount (third value) is positive or negative.
The break out of loop block provides an early exit from a loop. The following program prints "alpha" on the first iteration and "breaks out" of the loop on the second iteration when the loop variable is equal to "beta". The third item in the list is never reached.
The continue with next iteration (called continue in most programming languages) causes the remaining code in the body to be skipped and for the next iteration (pass) of the loop to begin.
The following program prints "alpha" on the first iteration of the loop. On the second iteration, the continue with next iteration block is run, skipping the printing of "beta". On the final iteration, "gamma" is printed.