Explain loops with examples

Loops are programming constructs that allow you to repeat a block of code multiple times. Here are some examples of loops:

Forever Loop:
A forever loop runs indefinitely until the program is stopped. Example:

forever {
move 10 steps
turn 90 degrees
}

This loop will move the sprite 10 steps and turn 90 degrees repeatedly forever.

Repeat Loop:
A repeat loop runs a block of code a specified number of times. Example:

repeat 5 {
move 10 steps
turn 90 degrees
}

This loop will move the sprite 10 steps and turn 90 degrees 5 times.

For Loop:
A for loop runs a block of code for each item in a list. Example:

for each item in list {
say item
}

This loop will say each item in the list.

While Loop:
A while loop runs a block of code as long as a condition is true. Example:

while (x < 5) {
move 10 steps
x = x + 1
}

This loop will move the sprite 10 steps and increment x by 1 until x is no longer less than 5.

Examples in Scratch:

  • Forever Loop: A sprite moving around the stage indefinitely.
  • Repeat Loop: A sprite drawing a shape 5 times.
  • For Loop: A sprite saying each item in a list of names.
  • While Loop: A sprite moving towards a target until it reaches it.

Loops are useful for repeating tasks, animations, and simulations, and are a fundamental concept in programming!

Leave a Comment

Your email address will not be published. Required fields are marked *