The "For-Loop" Block
-
Prerequisite
Description
When we repeat some code blocks in a loop, we often need to use a variable at the same time to keep track of the iterations. For example, below is a typical repeat loop:
The variable “index” is set as 1 initially, then we repeatedly say the value of “index” 3 times, and increase its value by 1 after each “say” block.
Since this is a very common use case, we can use a “for-loop” to simplify the program.
The “For” Block
The “for” block updates a variable repeatedly between an initial value and a limit value. For example, the follow for-loop will set the index value to 1 first, then keep increasing it by 2 in each step, and stop when it becomes 7 at the 4th iteration.
Parameters
- Index Variable: the variable that will be updated in each iteration. You can choose any variable from this dropdown to serve as the index variable.
- Initial Value: the value assigned to the index variable in the first iteration.
- Limit Value: the value limit for the index variable. If the index variable is increasing each step (positive step size), then the for-loop will stop whenever the index is more than the limit value; if the index variable is decreasing (negative step size), then the for-loop will stop whenever the index is less than the limit value.
- Step Size: how much the value of the index variable changes in each step. If we need to make the index variable decrease step by step, we set the limit value to be less than the initial value, and set the step size to be negative.
More Examples
A Larger Step Size
The Limit Value May Not Be the Last Value for the Index Variable
In the following example, the index variable increases by 2 each time. So after it reaches 5, it would become 7 if the for-loop continues. However, since the limit value is 6, we would stop when the index is 5.
A Negative Step Size
Make or Break a For-loop
To help you understand how for-loops work, the CreatiCode playground allows you to make or break a for-loop.
As shown below, for any for-loop, if you right-click on the “for” block, you will see an option to “break for-loop”. That command will convert the for-loop into a stack of blocks with no loops that do the same thing as the for-loop (the equivalent program).
As shown in the example, we first set the index variable to the initial value of 1, then run the 2 blocks inside the for-loop, then we change the index variable by the step size. This is repeated until the index variable reaches 5.
On the other hand, if you right-click on the stack of blocks, and select “make for-loop”, you will get a for-loop that gives the same result as this stack.
Note that the original for-loop has a limit value of 6, but after the “break” and “make” steps, the limit value becomes 5. This is fine, since both values would give the same result. -
-
-
-
-
-
-
-
-
-
-
-
-
-