Loops execute a statement or series of statements multiple times. The following are the loop blocks in Scratch:
The first loop repeats a fixed number of times as specified in its operand. The second and third repeat forever until the script stops (notice that they do not have notches at the bottom for additional statements to be attached. The difference between the second and third is that the second loops only if a certain condition is True. The fourth repeats until a certain condition becomes True.
A single run of a loop is called an iteration. Say we want to count to 10 using a loop. We will also need a counter variable. By convention, this is usually called something like K, J, or I (A, B, C, X, Y, and Z are usually used for variables so we don't use these names as counters). Create a variable called K as the counter. Then create a repeat loop that will run 10 times and place a "change K by 1" block inside the loop as shown below:
We can use the "say ... for ... secs" block inside of the loop to display the number for 0.5 sec then Run this program by clicking the Green Flag.
Excercise 2-5. In the following steps, we will write a program that computes the sum of the numbers from 1 to N where N is some variable input by the user.
Create a basic Green Flag event with a simple loop with K as a counter.
Read in a value from the user and store it in N (you will need to create the variable N of course). Before reading a value, say "Hi" for 1 second, "I will sum the values from 1 to N" for 2 seconds, and then "Enter a value for N:" as the caption for the ask block.
Make the loop run from 1 to N.
You simply need to set K's starting value to 1 and place the variable N in the operand of the repeat loop.
Create a new variable called Result. You will need to initialize Result to 0 first and then operate on Sum on each iteration of the loop in order to compute the sum from 1 to N. Finally, return the text "The sum from 1 to " [value of N] " is " [value of Result] Test your program with an N of 50 and 100 (the sums are 1275 and 5050 respectively). Hint: It is perfectly valid to set Result to itself + some variable.
In order to properly compute the sum, you should set Result to 0 outside the loop. Inside the loop you should set Result to Result + K because K will be incremented on each loop.
The result should look something like the following: